/*

Basic scripts

Copyright (c) 2006 InternetCrusade.com

*/

var arrHostName = location.hostname.split('.');

if(arrHostName[(arrHostName.length - 2)] == 'realtown') {
    var strBasePath = '/';
} else {
    var arrPath = location.pathname.split('/');
    var arrCleanPath = new Array();
    for(var x = 0; x < arrPath.length; x++) {
        if(arrPath[x].match('.php') || arrPath[x] == 'admin') {
            break;
        }
        arrCleanPath.push(arrPath[x]);
    }
    var strBasePath = arrCleanPath.join('/') + '/';
}

var boolImageUploader = true;


var arrImageSrc = new Array();
arrImages = new Array();

/*
arrImageSrc.push('img/ads/chase.png');
arrImageSrc.push('img/ads/domaindrivers.png');
arrImageSrc.push('img/ads/eneighborhoods.png');         //
arrImageSrc.push('img/ads/expresscopy.png');            //
arrImageSrc.push('img/ads/fidelityassets.png');         //
arrImageSrc.push('img/ads/floorplanonline.png');
arrImageSrc.push('img/ads/getyourhousesold.png');
arrImageSrc.push('img/ads/homes.com.png');
arrImageSrc.push('img/ads/lowes.png');
arrImageSrc.push('img/ads/marketingresultsgroup.png');
arrImageSrc.push('img/ads/mlsfinder.png');
arrImageSrc.push('img/ads/point2agent.png');            //
arrImageSrc.push('img/ads/powersites.png');
arrImageSrc.push('img/ads/psprint.png');
arrImageSrc.push('img/ads/rapattoni_spotlight.png');
arrImageSrc.push('img/ads/realeseller.png');
arrImageSrc.push('img/ads/realtytimes.png');
arrImageSrc.push('img/ads/relay.png');
arrImageSrc.push('img/ads/seminarsandsystems.png');
arrImageSrc.push('img/ads/sps.png');
arrImageSrc.push('img/ads/therealestateshow.png');      //
arrImageSrc.push('img/ads/usaselfemployed.png');
arrImageSrc.push('img/ads/visualtours.png');            //
arrImageSrc.push('img/ads/vreo.png');

for(var a = 0; a < arrImageSrc.length; a++) {    
    arrImages[a] = new Image();
    arrImages[a].src = arrImageSrc[a];
}
*/

var lastTabID = false;
var curImage = Math.ceil(Math.random() * 1000) % arrImageSrc.length;
var adTimer = 8000;


var windowWidth = 0;
var windowHeight = 0;





// Observe events

Event.observe(document, 'mousemove', moveToolTip, false);

Event.observe(window, 'load', function() {
    // Fix broken images
    /*
    for(var i = 0; i < document.images.length; i++) {
        if(!document.images[i].complete || (typeof document.images[i] != "undefined" && document.images[i].naturalWidth == 0)) {
            document.images[i].src = 'http://www.realtownblogs.com/img/avatars/default-60x73.png';
            if(document.images[i].hasClassName('avatar')) {
                document.images[i].src = 'http://www.realtownblogs.com/img/avatars/default-60x73.png';
            } else {
                document.images[i].src = 'http://beta.realtown.com/img/main/main_header_logo_gray.png';
            }
        }
    }
    */
    
    // News Flash
    if($('newsflash') && $('newsflash').style.display == 'none') {
        Effect.BlindDown('newsflash', {duration: 0.5});
    }
    
    
    // Get window width
    if(window.innerWidth && typeof(window.innerWidth) == 'number') {
        //Non-IE
        windowWidth = window.innerWidth;
        windowHeight = window.innerHeight;
    } else if(document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    
    
    // Position and size TabTips div.
    if($('tabinfo') && $('tdAll') && $('headcell')) {
        $('tabinfo').style.width = $('tdAll').getWidth();
        $('tabinfo').style.top = $('headcell').getHeight();
        var arrOffset = Position.cumulativeOffset($('headcell'));
        $('tabinfo').style.left = arrOffset[0];
    }
    
    
    // Observe tabs
    if($('tabinfo')) {
        if($('headarea')) {
            $('headarea').observe('mouseover', function(event){
                $('tabinfo').style.display = 'none';
                if(lastTabID && $(lastTabID)) {
                    //$(lastTabID).style.background='url(img/main/main_tab_ns_gray.png)';
                    //$(lastTabID).style.color='#333';
                    $(lastTabID).removeClassName('headerTabMo');
                    $(lastTabID).removeClassName('headerTabMoTip');
                    lastTabID = false;
                }
            });
        }
        
        if($('tdAll')) {
            $('tdAll').observe('mouseover', function(event){
                $('tabinfo').style.display = 'none';
                if(lastTabID && $(lastTabID)) {
                    //$(lastTabID).style.background='url(img/main/main_tab_ns_gray.png)';
                    //$(lastTabID).style.color='#333';
                    $(lastTabID).removeClassName('headerTabMo');
                    $(lastTabID).removeClassName('headerTabMoTip');
                    lastTabID = false;
                }
            });
        }
            
        if($('tdTabOption')) {
            $('tdTabOption').observe('mouseover', function(event){
                $('tabinfo').style.display = 'none';
                if(lastTabID && $(lastTabID)) {
                    //$(lastTabID).style.background='url(img/main/main_tab_ns_gray.png)';
                    //$(lastTabID).style.color='#333';
                    $(lastTabID).removeClassName('headerTabMo');
                    $(lastTabID).removeClassName('headerTabMoTip');
                    lastTabID = false;
                }
            });
        }
    }
    
    // Observe Search Box on Home Page
    if($('searchRealTown') && strSearchHelper) {
        $('searchRealTown').observe('focus', function(event){
            if($('searchRealTown').value == strSearchHelper) {
                $('searchRealTown').value = '';
            }
        });
        $('searchRealTown').observe('blur', function(event){
            if($('searchRealTown').value == '') {
                $('searchRealTown').value = strSearchHelper;
            }
        });
    }
});





/****  CUSTOM FUNCTIONS  ****/


function getLocationOptions(strField, strValue) {
    if(!strField || !strValue) return false;
    var strFilterValue      = strValue;
    var toFieldID           = '';
    var selectedValue       = '';
    var elementID           = '';
    var strType             = '';
    var strFilterName       = '';
    
    
    switch(strField) {
        case 'county':
            toFieldID           = 'intCountyID';
            selectedValue       = false;
            elementID           = 'tdSelCounty';
            strType             = 'counties';
            if(getOptions(strFilterValue, toFieldID, selectedValue, elementID, strType, strFilterName)) {
                toFieldID           = 'intCityID';
                selectedValue       = false;
                elementID           = 'tdSelCity';
                strType             = 'cities';
                strFilterName       = 'strStateID';
                getOptions(strFilterValue, toFieldID, selectedValue, elementID, strType, strFilterName);
            }
            break;
            
        case 'city':
            if(strValue == 0) {
                // Check state
                strFilterValue = $('strStateID').value;
                strFilterName       = 'strStateID';
            }
            toFieldID           = 'intCityID';
            selectedValue       = false;
            elementID           = 'tdSelCity';
            strType             = 'cities';
            getOptions(strFilterValue, toFieldID, selectedValue, elementID, strType, strFilterName);
            break;
    }
}

function getOptions(strFilterValue, toFieldID, selectedValue, elementID, strType, strFilterName) {
    if(strFilterValue && toFieldID && $(toFieldID)) {
        if(strType && strType.length > 0) {
            var strLoadingMessage = "Loading " + strType + ", please wait...";
        } else {
            var strLoadingMessage = "Loading options, please wait...";
        }
        showLoading(strLoadingMessage);
        // Save original field value
        var origValue = $(toFieldID).value;
        // Disable select field temporarily
        // Form.Element.disable($(toFieldID));
        
        var handlerFunc = function(t) {
            hideLoading();
            // Form.Element.enable($(toFieldID));
            if(t.responseText.length > 0) {
                var arrResponse = t.responseText.evalJSON(true);
                if(arrResponse.length > 0) {
                    var arrOptions = $(toFieldID).immediateDescendants();

                    // Remove all existing items first
                    for(var i = 0; i < arrOptions.length; i++) {
                        arrOptions[i].remove();
                    }

                    // Add new ones
                    var y = '';
                    for(i = 0; i < arrResponse.length; i++) {
                        y = document.createElement('option');
                        y.text = arrResponse[i].theTitle;
                        y.value = arrResponse[i].theValue;
                        try{
                            $(toFieldID).add(y, null);
                        } catch(ex) {
                            $(toFieldID).add(y);
                        }
                    }
                }
                
                if(selectedValue) {
                    $(toFieldID).value = selectedValue;
                } else {
                    $(toFieldID).value = '0';
                    $(toFieldID).value = origValue;
                }
                
                return true;
            }
        }
        
        var errFunc = function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
        
        var postData  = 'get=options';
        if(strType) {
            postData += '&type=' + encodeURIComponent(strType);
        }
        postData += '&filter=' + encodeURIComponent(strFilterValue);

        if(strFilterName && strFilterName.length > 0) {
            postData += '&strFilterName=' + encodeURIComponent(strFilterName);
        }

        if(selectedValue) {
            postData += '&set=' + encodeURIComponent(selectedValue);
        }
        //alert('post: ' + postData);
        new Ajax.Request(strBasePath + 'myrealtown/myrealtown_ajax.php', {method:'post', postBody:postData, onSuccess:handlerFunc, onFailure:errFunc});
    }
}


function playMedia(strType, strSrc, strDiv) {
    if(strType && strSrc && strDiv && $(strDiv)) {
        var postData  = 'task=play';
            postData += '&type=' + encodeURIComponent(strType);
            postData += '&src=' + encodeURIComponent(strSrc);
        new Ajax.Updater($(strDiv), strBasePath + 'ajax.php', {method:'post', postBody:postData});
    }
}


function saveOption(theOption, theValue) {
    if(theOption) {
        switch(theOption) {
            case 'showTabTips':
                if(lastTabID && $(lastTabID)) {
                    $(lastTabID).removeClassName('headerTabMo');
                    $(lastTabID).removeClassName('headerTabMoTip');
                }
                lastTabID = false;
                break;
                
            
            default:
                
        }
        
        if(theValue === true) {
            theValue = 1;
            //alert('true');
        } else if(theValue === false) {
            theValue = ''
            //alert('false');
        }
        Cookie.set(theOption, theValue, 7776000);
    }
}


function selectFeedTab(strTabID, ajax, url) {
    if(strTabID && $('feedCurrent') && $('feedTab' + strTabID)) {
        // Reset all tabs
        if($('curFeedID') && $('curFeedID').innerHTML) {
            // alert('feedTab' + $('curFeedID').innerHTML);
            if($('feedTab' + $('curFeedID').innerHTML)) {
               $('feedTab' + $('curFeedID').innerHTML).removeClassName('sel'); 
            }
        }
        if($('divLoading')) {
            $('feedCurrent').innerHTML = '<div style=\'width: 200px; margin: 10px auto; text-align: center; background: #fff; border: 1px solid #ccc; \'>' + $('divLoading').innerHTML + '<br \/>Loading feed, please wait...<\/div>';
        } else {
            $('feedCurrent').innerHTML = 'Loading feed, please wait...';
        }
        if(ajax) {
            var postData  = 'view=rss';
            if(url) {
                postData += '&url=' + encodeURIComponent(url);
            } else {
                postData += '&feed=' + encodeURIComponent(strTabID.substr(1));
            }
            new Ajax.Updater($('feedCurrent'), strBasePath + 'ajax.php', {method:'post', postBody:postData});
            $('feedTab' + strTabID).addClassName('sel');
        } else {
            if($('feed' + strTabID)) {
                $('feedTab' + strTabID).addClassName('sel');
                $('feedCurrent').innerHTML = $('feed' + strTabID).innerHTML;
            }
        }
        if($('curFeedID')) {
            $('curFeedID').innerHTML = strTabID;
        }
    }
}


function fckQuote(strQuoteID, strFckEditorID, strAuthorID, boolStripQuotes) {
    if(strQuoteID && $(strQuoteID) && strFckEditorID && FCKeditorAPI.GetInstance(strFckEditorID)) {
        var objEditor = FCKeditorAPI.GetInstance(strFckEditorID);
        var htmlQuote = '';
        
        objQuote = document.createElement('div');
        objQuote.id = 'tmp' + strQuoteID;
        $(strQuoteID).appendChild(objQuote);
        objQuote.innerHTML = $(strQuoteID).innerHTML;

        // Remove quotes from the quote.
        if(boolStripQuotes) {
            // Remove Quotes
            var arrQuotes = $('tmp' + strQuoteID).getElementsByClassName('commentQuote');
            for(var i = 0; i < arrQuotes.length; i++) {
                arrQuotes[i].remove();
            }
            // Remove BR tags
            var arrBrs = $('tmp' + strQuoteID).getElementsByClassName('brQuote');
            for(var i = 0; i < arrBrs.length; i++) {
                arrBrs[i].remove();
            }
        }
        

        htmlQuote += '<div class=\'commentQuote\' id=\'cqd' + strQuoteID + '\'>';
        if(strAuthorID && $(strAuthorID)) {
            htmlQuote += '<div class=\'commentQuoteAuthor\' id=\'cqa' + strQuoteID + '\'>Quoting ' + $(strAuthorID).innerHTML + ':</div>';
        }
        htmlQuote += objQuote.innerHTML + '</div><br class=\'brQuote\' \/>';
        
        $('tmp' + strQuoteID).remove();
        
        objEditor.InsertHtml(htmlQuote);
        objEditor.Focus();
        return false; // Prevent anchor from going to a new page.
    }
}


// doPostComment: Submits comment to ajax.php for processing.
function doPostComment(pkArticleId) {
    if(eval('document.formPostComment' + pkArticleId) && document.getElementById('postcom' + pkArticleId)) {
        var theForm = eval('document.formPostComment' + pkArticleId);
        var theDiv = document.getElementById('postcom' + pkArticleId);
        var divPostComment = document.getElementById('postcom' + pkArticleId);
        var divPostCommentResponse = document.getElementById('postcomres' + pkArticleId);
        var oEditor = FCKeditorAPI.GetInstance('strComment' + pkArticleId);
        
        var postData = 'post=comment';
        if(theForm.strName) {
            var strName = theForm.strName.value;
            if(strName.length == 0) {
                alert('Please provide your name before submitting your comment.');
                return false;
            }
            postData += '&strName=' + encodeURIComponent(strName);
        }
        if(theForm.strEmail) {
            var strEmail = theForm.strEmail.value;
            if(strEmail.length == 0) {
                alert('Please provide your E-mail address before submitting your comment.');
                return false;
            }
            postData += '&strEmail=' + encodeURIComponent(strEmail);
        }
        /*
        if(theForm.strWebsite) {
            strWebsite = theForm.strWebsite.value;
            postData += '&strWebsite=' + encodeURIComponent(strWebsite);
        }
        */
        if(theForm.strVerificationCode) {
            strVerificationCode = theForm.strVerificationCode.value;
            if(strVerificationCode.length == 0) {
                alert('Please enter the verification code before submitting your comment.');
                return false;
            }
            postData += '&strValidationID=' + encodeURIComponent(theForm.strValidationID.value);
            postData += '&strVerificationCode=' + encodeURIComponent(strVerificationCode);
        }
        
        var strSubject = theForm.strSubject.value;
        var strComment = oEditor.EditorDocument.body.innerHTML;
        if(strComment.length == 0) {
            alert('You must enter a comment to post a comment.');
            return false;
        }
        if(strName && strEmail) { // && strWebsite) {
            if(theForm.cbRemember) {
                if(theForm.cbRemember.checked == true) {
                    cbRemember = 1;
                } else {
                    cbRemember = 0;
                }
            } else {
                cbRemember = 0;
            }
            postData += '&cbRemember=' + encodeURIComponent(cbRemember);
        }
        
        postData += '&pkArticleId=' + encodeURIComponent(pkArticleId);
        postData += '&strSubject=' + encodeURIComponent(strSubject);
        postData += '&strComment' + encodeURIComponent(pkArticleId) + '=' + encodeURIComponent(strComment);

        divPostCommentResponse.style.display = 'block';
        new Ajax.Updater(divPostCommentResponse, strBasePath + 'ajax.php', {method:'post', postBody:postData});
        updateCommentCount(pkArticleId);
    }
}




// updateCommentCount: Updates the number of comments in the "View Comments" and "Hide Comments" links
function updateCommentCount(pkArticleId) {
    if(document.getElementById('numCommentsView' + pkArticleId) && document.getElementById('numCommentsHide' + pkArticleId)) {
        var handlerFunc = function(t) {
            intNumComments = (t.responseText);
            divNumCommentsHide.innerHTML = intNumComments;
            divNumCommentsView.innerHTML = intNumComments;
        }
        
        var errFunc = function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
    
        divNumCommentsView = document.getElementById('numCommentsView' + pkArticleId);
        divNumCommentsHide = document.getElementById('numCommentsHide' + pkArticleId);
        var postData =  'total=comments';
            postData += '&pkArticleId=' + pkArticleId;
        new Ajax.Request(strBasePath + 'ajax.php', {method:'post', postBody:postData, onSuccess:handlerFunc, onFailure:errFunc});
    }
}




// showPostCommentBox: creates a "post comment" box so the user can post a comment. Default comment is to entry of type 'article'.
function showPostCommentBox(pkArticleId, forceShow) {
    if(document.getElementById('com' + pkArticleId)) {
        divComments = document.getElementById('com' + pkArticleId);
        divComments.style.borderBottom = '0px';
    }
    if(document.getElementById('postcom' + pkArticleId)) {
        divPostComment = document.getElementById('postcom' + pkArticleId);
        if(divPostComment.style.display == 'none' || forceShow) {
            divPostComment.style.display = 'block';
            if(divPostComment.innerHTML == '' || forceShow) {
                postData =  'create=postcomment';
                postData += '&pkArticleId=' + pkArticleId;
                new Ajax.Updater(divPostComment, strBasePath + 'ajax.php', {method:'post', postBody:postData});
            }
        }
        // Element.scrollTo(divPostComment);
    }
}


// showArticle: displays the article by page number (optional, default page 1) or full article (page '0')
function showArticle(pkArticleId, intPage) {
    if($('art' + pkArticleId)) {
        showLoading('Please wait while the selected article loads...');
        if($('teaser' + pkArticleId)) {
            $('teaser' + pkArticleId).style.display = 'none';
        }

        $('art' + pkArticleId).style.display = 'block';
        
        var postData  = 'view=article';
            postData += '&pkArticleId=' + pkArticleId;
        if(intPage && intPage >= 0) {
            postData += '&intPage=' + intPage;
        }
        
        var handlerFunc = function(t) {
            var strResponse = (t.responseText);
            if($('art' + pkArticleId)) {
                $('art' + pkArticleId).innerHTML = strResponse;
            }
            showLoading();
        }
        
        var errFunc = function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
    
        new Ajax.Request(strBasePath + 'ajax.php', {method:'post', postBody:postData, onSuccess:handlerFunc, onFailure:errFunc});
        updateCommentCount(pkArticleId);
    }
}



// toggleComments: shows or hides article comments.
function toggleComments(pkArticleId, intStart, intCommentsPerPage, boolForceOpen) {
    if(!intStart) {
        intStart = 0;
    }
    if(!intCommentsPerPage) {
        intCommentsPerPage = 10;
    }
    if(document.getElementById('linkViewComments' + pkArticleId) && document.getElementById('linkHideComments' + pkArticleId) && document.getElementById('com' + pkArticleId)) {
        elemLinkView = document.getElementById('linkViewComments' + pkArticleId);
        elemLinkHide = document.getElementById('linkHideComments' + pkArticleId);
        elemDiv = document.getElementById('com' + pkArticleId);
        if(elemDiv.style.display == 'none' || boolForceOpen) {
            elemLinkView.style.display = 'none';
            elemLinkHide.style.display = 'inline';
            elemDiv.style.display = 'block';
            if(elemDiv.innerHTML == '' || boolForceOpen) {
                // perform Ajax request
                if(elemDiv.innerHTML == '') {
                    elemDiv.innerHTML = '<span style=\'color: #999;\'>Loading comments, please wait...<\/span>';
                }
                postData = 'view=comments&pkArticleId=' + pkArticleId + '&intStart=' + intStart + '&intCommentsPerPage=' + intCommentsPerPage;
                new Ajax.Updater(elemDiv, strBasePath + 'ajax.php', {method:'post', postBody:postData});
                // Element.scrollTo(elemDiv);
            }
        } else {
            elemLinkView.style.display = 'inline';
            elemLinkHide.style.display = 'none';
            elemDiv.style.display = 'none';
        }
    }
    updateCommentCount(pkArticleId);
}
var xPos = 0;
var hoverbox = false;
var toHideHoverBox = false;
var effectFadeHoverBox = false;

// Cute little hover box (custom ACRONYM)
function showHoverBox(strHTML, strParameters, boolUseDiv) {
    var theHoverDiv = 'divHoverBox';
    if($(theHoverDiv) && strHTML.length > 0) {
        if(toHideHoverBox) {
             clearTimeout(toHideHoverBox);
             toHideHoverBox = false;
        }
        /*
        if(effectFadeHoverBox) {
             effectFadeHoverBox = false;
             $('divHoverBox').style.opacity = '1.0';
        }
        */
        // $('divHoverBox').show();
        hoverbox = true;
        // Default parameters
        var arrParameters = new Array();
        arrParameters['width']          = 300;      // Default maximum width of the box
        arrParameters['height']         = 'auto';       // 'auto' or specify (ex: 400px)
        arrParameters['padding']        = 4;        // Default padding
        arrParameters['margin']         = 4;
        arrParameters['top']            = 4;
        arrParameters['left']           = 4;
        arrParameters['opacity']        = '0.75';
        
        if(strParameters) {
            // TODO: custom parameters.
        } else {
            var strParameters = '';
        }
        
        if(boolUseDiv) {
            if($(strHTML) && $(strHTML).innerHTML.length > 0) {
                strHTML = $(strHTML).innerHTML;
            }
        }
        
        var arrCleanParameters = new Array();
        for(var i in arrParameters) {
            arrCleanParameters.push(i + ': ' + arrParameters[i] + ';');
        }
        
        if(arrCleanParameters.length > 0) {
            strParameters = arrCleanParameters.join(' ');
        }
        
        // var divHoverBox = document.getElementById('divHoverBox');
        $(theHoverDiv).innerHTML = strHTML;
        // divHoverBox.style.opacity = '0.0';
        $(theHoverDiv).style.display = 'block';
        // Effect.Appear('divHoverBox', { duration: 0.3 });
        doMoveToolTip();
        // moveToolTip();
        // eval("divHoverBox.style.width = ''");
        var dimensions = Element.getDimensions($('divHoverBox'));
        if(dimensions.width > arrParameters['width']) {
            $(theHoverDiv).style.width = arrParameters['width'];
        } else {
            // eval("divHoverBox.style.width = ''");
        }
    }
}

/* This functionality didn't work out too well.
function disablePage(boolSet) {
    if($('disablePage')) {
        if(boolSet) {
            if(window.innerWidth) {
                var intPageWidth = window.innerWidth;
                var intPageHeight = window.innerHeight;
                var intPageScrollTop = window.pageYOffset;
                var intPageScrollLeft = window.pageXOffset;
            } else if(document.body && document.body.offsetWidth) {
                var intPageWidth = document.body.offsetWidth;
                var intPageHeight = document.body.offsetHeight;
                var intPageScrollTop = document.body.scrollTop;
                var intPageScrollLeft = document.body.scrollLeft;
            }
            document.body.style.overflow = 'hidden';
            $('disablePage').style.width = '100%';
            $('disablePage').addClassName('true');
            $('disablePage').style.height = intPageHeight;
            alert('page disabled');
        } else {
            $('disablePage').removeClassName('true');
            alert('page enabled');
            document.body.style.overflow = 'auto';
        }
    } else {
        alert('error');
    }
}
*/

var currentMousePositionX = 0;
var currentMousePositionY = 0;
var lastMousePositionX = 0;
var lastMousePositionY = 0;

function moveToolTip(e) {
    //if($('divHoverBox') && $('divHoverBox').style.display == 'block') {
        lastMousePositionX = currentMousePositionX;
        lastMousePositionY = currentMousePositionY;
        currentMousePositionX = Event.pointerX(e);
        currentMousePositionY = Event.pointerY(e);
        doMoveToolTip();
    //}
}

function doMoveToolTip() {
    if($('divHoverBox') && $('divHoverBox').style.display == 'block') {
        if(window.innerWidth) {
            var intPageWidth = window.innerWidth;
            var intPageHeight = window.innerHeight;
            var intPageScrollTop = window.pageYOffset;
            var intPageScrollLeft = window.pageXOffset;
        } else if(document.body && document.body.offsetWidth) {
            var intPageWidth = document.body.offsetWidth;
            var intPageHeight = document.body.offsetHeight;
            var intPageScrollTop = document.body.scrollTop;
            var intPageScrollLeft = document.body.scrollLeft;
        }
        if(($('divHoverBox').getWidth() + currentMousePositionX + 36) > (intPageWidth + intPageScrollLeft)) {
            $('divHoverBox').style.left = intPageWidth - $('divHoverBox').getWidth() + intPageScrollLeft - 24;
        } else {
            $('divHoverBox').style.left = currentMousePositionX + 12;
        }
        if(($('divHoverBox').getHeight() + currentMousePositionY + 1) > (intPageHeight + intPageScrollTop)) {
            $('divHoverBox').style.top = intPageHeight - $('divHoverBox').getHeight() + intPageScrollTop - 1;// - 24;
        } else {
            $('divHoverBox').style.top = currentMousePositionY;
        }
    }
}




function hideHoverBox() {    
    hoverbox = false;
    var theHoverDiv = 'divHoverBox';
    if($(theHoverDiv)) {
        // $('divHoverBox').style.display = 'none';
        if(!toHideHoverBox) {
            toHideHoverBox = setTimeout("doHideHoverBox('" + theHoverDiv + "')", 20);
        }
    }
}

function doHideHoverBox(theBox) {
    if(theBox && $(theBox)) {
        $(theBox).hide();
        //effectFadeHoverBox = new Effect.Fade('divHoverBox', { duration: 0.15 });
    }
}

var errorLimit = false;

function showRemaining(elemid, maxlength) {
    remainingLength = maxlength - $F(elemid).length;
    if(remainingLength < 0) {
        $('chrem' + elemid).style.color = '#f00';
        remainingLength = -(remainingLength) + ' CHARACTERS OVERLIMIT';
        errorLimit = elemid;
    } else {
        $('chrem' + elemid).style.color = 'inherit';
        errorLimit = false;
    }
    $('chrem' + elemid).innerHTML = remainingLength;
}

function fadeElement(strElement, intStartOpacity, intEndOpacity, intSteps) {
    // Fades element from start opacity to end opacity (values 0-100)
    if(!intStartOpacity == undefined) {
        var intStartOpacity = 0;
    }
    if(intEndOpacity == undefined) {
        var intEndOpacity = 100;
    }
    if(!intSteps) {
        var intSteps = 100;
    }
    var intOpacity = 0;
    for(var i = 0; i < intSteps; i++) {
        intOpacity = Math.ceil(intStartOpacity + (i * ((intEndOpacity - intStartOpacity) / intSteps))) / 100;
        setOpacity(strElement, intOpacity);
    }
    setOpacity(strElement, intEndOpacity);
}

function setOpacity(strElement, intOpacity) {
    if(strElement) {
        strElement.style.opacity = intOpacity;
    }
}

function showListMessage(strList, pkPostId) {
    if(document.getElementById('trunc' + pkPostId) && document.getElementById('msg' + pkPostId)) {
        divTrunc = document.getElementById('trunc' + pkPostId);
        divMsg = document.getElementById('msg' + pkPostId);
        
        divTrunc.style.display = 'none';
        divMsg.style.display = 'block';
        
        if(divMsg.innerHTML.length == 0) {
            divMsg.innerHTML = '<div style=\'color: #555; font-size: 12px;\'>Please wait while the selected message loads...<\/div>';
        }
        
        postData =      'view=listmessage';
        postData +=     '&strList=' + strList;
        postData +=     '&pkPostId=' + pkPostId;
        new Ajax.Updater(divMsg, strBasePath + 'ajax.php', {method:'post', postBody:postData});
        // Element.scrollTo(divMsg);
    }
}

function insertImage(strImageUrl, strEditorName) {
    // Check if strEditorName is FCK instance
    if(FCKeditorAPI.GetInstance(strEditorName)) {
        var oEditor = FCKeditorAPI.GetInstance(strEditorName);
        var strImageHtml = '<img src="' + strImageUrl + '" border="0" alt="" \/>';
        oEditor.InsertHtml(strImageHtml);
    } else if($(strEditorName)) {
        $(strEditorName).src = strImageUrl;
    } else {
        alert('Unable to find target editor.');
    }
    if(formProfile && formProfile.strAvatarURL) {
        formProfile.strAvatarURL.value = strImageUrl;
        if($('strAvatarURLText')) {
            $('strAvatarURLText').innerHTML = strImageUrl;
        }
    }
}

function makeNewWindow(strUrl, intWidth, intHeight) {
    if(!intWidth) {
        intWidth = 750;
    }
    if(!intHeight) {
        intHeight = 540;
    }
    newWindowLeft = (Math.ceil((screen.width / 2) - (intWidth / 2)));
    newWindowTop = (Math.ceil((screen.height / 2) - (intHeight / 2)) - 40);
    if(newWindowLeft < 5) {
        newWindowLeft = 5;
    }
    if(newWindowTop < 5) {
        newWindowTop = 5;
    }
    window.open(strUrl, 'a' + Math.floor(Math.random()*10000), 'width=' + intWidth + ',height=' + intHeight + ',resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=yes,menubar=no,copyhistory=no,left=' + newWindowLeft + ',top=' + newWindowTop + ',screenX=' + newWindowLeft + ',screenY=' + newWindowTop + '');
	return false;
}

function makeNewIM() {
    intWidth = 240;
    intHeight = 600;
    newWindowLeft = (Math.ceil((screen.width / 2) - (intWidth / 2)));
    newWindowTop = (Math.ceil((screen.height / 2) - (intHeight / 2)) - 40);
    if(newWindowLeft < 5) {
        newWindowLeft = 5;
    }
    if(newWindowTop < 5) {
        newWindowTop = 5;
    }
    window.open('im.php', 'rtIM', 'width=' + intWidth + ',height=' + intHeight + ',resizable=yes,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=' + newWindowLeft + ',top=' + newWindowTop + ',screenX=' + newWindowLeft + ',screenY=' + newWindowTop);
	return false;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function findRelativePos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
	}
	return [curleft,curtop];
}

function showImageUploader(strFilePath) {
    if(boolImageUploader) {
        var strUrl = strBasePath + 'fileupload.php?type=image';
        if(strFilePath && strFilePath.length > 0) {
            strUrl += '&strFilePath=' + encodeURIComponent(strFilePath);
        }
        makeNewWindow(strUrl, 400, 350);
    } else {
        alert('Please use the Insert/Add Image button\non the Editor Toolbar to upload new images.');
    }
}

function showAllImages(boolRefresh, strSearchPhrase) {
    if($('allImages')) {
        $('allImages').style.position = 'absolute';

        // Check cookie for saved position
        if(Cookie.accept() && Cookie.get('divAllImagesPosition')) {
            var savedPosition = Cookie.get('divAllImagesPosition').split(',', 2);
            if(savedPosition.length == 2) {
                $('allImages').style.left = savedPosition[0];
                $('allImages').style.top = savedPosition[1];
                if($('allImagesContent').innerHTML == '') {
                    $('allImagesContent').innerHTML = ' ';
                }
            }
        }

        if($('allImagesContent').innerHTML == '') {
            // This must be the first time it is opened. Set position before filling it with contents.
            if(document.body && document.body.clientWidth) {
                var divPosX = document.body.scrollLeft + Math.ceil(document.body.clientWidth / 2) - 250;
                var divPosY = document.body.scrollTop + 25;
                var divWidth = document.body.clientWidth - 50;
                var divHeight = document.body.clientHeight - 50;
            } else if(window.innerHeight && window.pageYOffset && window.innerWidth && window.pageXOffset) {
                var divPosX = window.pageXOffset + 25;
                var divPosY = window.pageYOffset + 25;
                var divWidth = window.innerWidth - 50;
                var divHeight = window.innerHeight - 50;
            } else {
                var divPosX = 200;
                var divPosY = 100;
                var divWidth = 500;
                var divHeight = 300;
            }
            $('allImages').style.top = divPosY;
            $('allImages').style.left = divPosX;
        }

        $('allImages').style.display = 'block';
        var strParam  = 'show=allimages';
        if(strSearchPhrase) {
            strParam += '&search=' + encodeURIComponent(strSearchPhrase);
        }
        if(boolRefresh || $('allImagesContent').innerHTML == '' || $('allImagesContent').innerHTML == ' ') {
            $('allImagesContent').innerHTML = 'Loading, please wait...';
            new Ajax.Updater($('allImagesContent'), '../ajax.php', {method:'post', postBody:strParam});
        }
        // Drag the element!
        dragAllImages = new Draggable('allImages', {handle: 'allImagesHandle', starteffect: '', endeffect: ''});
    } else {
        alert('Requred div was not found.');
    }
}

function starItem(strItemID, enumSource, strIdPrefix, intListID) {
    if(strItemID && enumSource && $(strIdPrefix + strItemID)) {
        var starItemHandler = function(t) {
            var response = t.responseText;
            if(response == 'fail') {
                alert("You are not allowed to star this item.");
                return;
            }
            if(response == 1) {
                $(strIdPrefix + strItemID).src = 'img/buttons/star_on.png';
            } else {
                $(strIdPrefix + strItemID).src = 'img/buttons/star_off.png';
            }
        }
        
        var starItemError = function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
        
        var postData  = 'task=star';
            postData += '&strItemID=' + encodeURIComponent(strItemID);
            postData += '&enumSource=' + encodeURIComponent(enumSource);
        if(intListID) {
            postData += '&intListID=' + encodeURIComponent(intListID);
        }
        new Ajax.Request(strBasePath + 'ajax.php', {method:'post', postBody:postData, onSuccess:starItemHandler, onFailure:starItemError});
    }
}

function hideAllImages() {
    if($('allImages')) {
        // Save current position in Cookie
        if(Cookie.accept) {
            Cookie.set('divAllImagesPosition', $('allImages').style.left + ',' + $('allImages').style.top, 7776000);
        }
        $('allImages').hide();
        /*
        if(dragAllImages) {
            dragAllImages.destroy();
        }
        */
    }
}

function showAvailableImages(strElementId, intPage, intImagesPerPage, strUsername) {
    if(!intImagesPerPage) {
        var intImagesPerPage = 20;
    }
    if(!intPage) {
        intPage = 1;
    }
    if($(strElementId + '_sc')) {
        intHeight = $(strElementId + '_sc').style.height;
        intWidth = $(strElementId + '_sc').style.width;
        if(!strUsername) {
            var strUsername = Cookie.get('strICUsername');
        }
        var strParam = '';
        // $_GET[width], $_GET[height], $_GET[strFieldName], $_GET[strFormName], $_GET[page], $_GET[ajax]
        strParam +=     'create=imagetoolbar';
        strParam +=     '&strUsername=' + strUsername;
        strParam +=     '&page=' + intPage;
        if(intWidth) {
            strParam +=     '&width=' + intWidth;
        }
        if(intHeight) {
            strParam +=     '&height=' + intHeight;
        }
        if(strElementId) {
            strParam +=     '&strFieldName=' + strElementId;
        }
        // alert(strParam);
        new Ajax.Updater($(strElementId + '_td'), '../ajax.php', {method:'post', postBody:strParam});
    } else {
        alert('Unable to locate target element.');
    }
}

function doUploadImage(strFieldName, strFormName) {
    if(strFormName && strFieldName) {
        if(eval('document.' + strFormName + '.' + strFieldName)) {
            strImage = eval('document.' + strFormName + '.' + strFieldName);
            alert(strImage);
        }
    }
}

function updateLogin(strType) {
    if(strType == 'loginform') {
        $('loggedout').style.display = 'none';
        $('loginform').style.display = 'block';
    } else if(strType == 'loggedout') {
        $('loggedout').style.display = 'block';
        $('loginform').style.display = 'none';
        
    }
}

function showSearchMode(strSearchMode) {
    if(strSearchMode == 'advanced') {
        $('searchAdv').style.display = 'block';
        $('searchWordBas').style.display = 'inline';
        $('searchWordAdv').style.display = 'none';
        document.formSearch.adv.value = 1;
        Cookie.set('searchAdvanced', '1', 31536000);
    } else {
        $('searchAdv').style.display = 'none';
        $('searchWordBas').style.display = 'none';
        $('searchWordAdv').style.display = 'inline';
        document.formSearch.adv.value = 0;
        Cookie.set('searchAdvanced', '0', 31536000);
    }
}

function cleanSubmitSearch() {
    if(document.formSearch.adv.value == 0 || document.getElementById('searchAdv').style.display == 'none') {
        var strUrl = '/search.php?search=' + document.formSearch.search.value;
        window.location.href = strUrl;
    } else {
        document.formSearch.submit();
    }
}

function setFormValue(strField, strValue) {
    if($F(strField)) {
        $F(strField).value = strValue;
    }
}

function makeTextArea(strDivId, strField, strValue, strParameters) {
    if(!strField) {
        var strField = 'textarea';
    }
    if(!strValue) {
        var strValue = '';
    }
    if(!strParameters) {
        strParameters = '';
    }
    strTextArea = '<textarea class=friendly name=\'' + strField + '_text\' ' + strParameters + '>' + strValue + '<\/textarea>';
    if($(strDivId)) {
        $(strDivId).innerHTML = strTextArea;
    }
}

function showLoading(strCustomText) {
    // window.innerHeight  == Inner height of the window.
    // window.innerWidth   == Inner Width of the window.
    // window.pageXOffset  == Scroll offset from left of page.
    // window.pageYOffset  == Scroll offset from top of page.
    
    if($('divLoading')) {
        if($('divLoading').style.display == 'block') {
            $('divLoading').style.display = 'none';
        } else {
            $('divLoading').style.position = 'absolute';
            if(document.body && document.body.clientWidth) {
                var divPosX = document.body.scrollLeft + ( Math.ceil(document.body.clientWidth / 2) - 150 );
                var divPosY = document.body.scrollTop + ( Math.ceil(document.body.clientHeight / 2) - 100 );
            } else if(window.innerHeight && window.pageYOffset && window.innerWidth && window.pageXOffset) {
                var divPosX = window.pageXOffset + ( Math.ceil(window.innerWidth / 2) - 150 );
                var divPosY = window.pageYOffset + ( Math.ceil(window.innerHeight / 2) - 100 );
            } else {
                var divPosX = 200;
                var divPosY = 100;
            }
            $('divLoading').style.top = divPosY;
            $('divLoading').style.left = divPosX;
            
            if($('divLoadingText')) {
                if(strCustomText) {
                    $('divLoadingText').innerHTML = strCustomText;
                } else {
                    $('divLoadingText').innerHTML = '';
                }
            }
            
            $('divLoading').style.display = 'block';
        }
    }
}

function hideLoading() {
    if($('divLoading')) {
        if($('divLoading').style.display == 'block') {
            $('divLoading').style.display = 'none';
        }
    }
}

function clearSearchHistory() {
    if(Cookie.accept()) {
        Cookie.erase('strSavedSearches');
    }
    if($('searchHistory')) {
        $('searchHistory').innerHTML = '<span style=\'color: #777;\'>Search history is empty.<\/span>';
    }
}

function clearForm(elemFormID) {
    if(elemFormID && $(elemFormID)) {
        var arrFields = Form.getElements($(elemFormID));
        if(arrFields.length > 0 && confirm("Are you sure you want to clear this form?")) {
            for(var i = 0; i < arrFields.length; i++) {
                //alert(arrFields[i].type);
                switch(arrFields[i].type) {
                    case 'text':
                    case 'textarea':
                    case 'password':
                    case 'file':
                        $(elemFormID)[i].clear();
                        break;
                    
                    case 'select-one':
                        $(elemFormID)[i].selectedIndex = 0;
                        break;
                        
                    case 'select-multiple':
                        $(elemFormID)[i].selectedIndex = -1;
                        break;
                        
                    case 'checkbox':
                    case 'radio':
                        $(elemFormID)[i].checked = false;
                        break;
                        
                }
            }
        }
    }
}

function checkPasswordStrength(objFormField) {
    if(objFormField && $('pws_outer') && $('pws_inner') && $('pws_text')) {
        if(objFormField.value.length < 6) {
            $('pws_inner').style.width = '1px';
            $('pws_inner').style.backgroundColor = '#f00';
            $('pws_inner').style.borderBottom = '2px solid #f00';
            $('pws_inner').style.borderTop = '2px solid #f00';
            $('pws_text').innerHTML = '<span style=\'color: #c00;\'>6 Characters Minimum<\/span>';
            return;
        }
        var alpha = false;
        var integer = false;
        var intCountInteger = 0;
        var intCountAlpha = 0;
        var intStrength = 0;
        var intMaxStrength = 100000;
        var intMaxWidth = parseInt($('pws_outer').style.width.replace('px', ''));
        
        var intRedStart = 225;
        var intGreenStart = 20;
        var intBlueStart = 40;
        
        var intRedEnd = 20;
        var intGreenEnd = 225;
        var intBlueEnd = 50;
        
        intStrength = (objFormField.value.length - 3) * 350;
        for(var i = 0; i < objFormField.value.length; i++) {
            if(isFinite(objFormField.value.substr(i, 1))) {
                intStrength *= 1.5;
                integer = true;
                intCountInteger++;
            } else {
                intStrength *= 1.3;
                alpha = true;
                intCountAlpha++;
            }
        }

        // Bonus multiplier for using both letters and numbers
        if(integer == true && alpha == true) {
            intStrength *= 1.2;
        }
        
        // Bonus multiplier for use of many letters and many numbers
        intStrength += intCountAlpha * intCountInteger * 1000; // objFormField.value.length;

        if(intStrength > intMaxStrength) {
            intStrength = intMaxStrength;
        }

        // Set Width
        $('pws_inner').style.width = Math.ceil(intMaxWidth * intStrength / intMaxStrength) + 'px';
        
        // Set Color
        var intRed = Math.ceil((intRedEnd - intRedStart) * (intStrength / intMaxStrength) + (intRedStart));
        var intGreen = Math.ceil((intGreenEnd - intGreenStart) * (intStrength / intMaxStrength) + (intGreenStart));
        var intBlue = Math.ceil((intBlueEnd - intBlueStart) * (intStrength / intMaxStrength) + (intBlueStart));
        $('pws_inner').style.backgroundColor = 'RGB(' + intRed + ', ' + intGreen + ', ' + intBlue + ')';
        $('pws_inner').style.borderBottom = '2px solid RGB(' + Math.ceil(intRed * 0.6) + ', ' + Math.ceil(intGreen * 0.6) + ', ' + Math.ceil(intBlue * 0.6) + ')';
        $('pws_inner').style.borderTop = '2px solid RGB(' + Math.ceil(intRed * 1.3) + ', ' + Math.ceil(intGreen * 1.3) + ', ' + Math.ceil(intBlue * 1.3) + ')';
        
        // Set Strength
        if(intStrength == 100000) {
            $('pws_text').innerHTML = '<strong>Very Strong!<\/strong>';
        } else if(intStrength > 65000) {
            $('pws_text').innerHTML = 'Strong';
        } else if(intStrength > 25000) {
            $('pws_text').innerHTML = 'Medium';
        } else {
            $('pws_text').innerHTML = 'Weak';
        }
    }
}

function glowTab(pkStrucId, theEvent, isSelected) {
    if(pkStrucId && $('tab' + pkStrucId) && theEvent) {
        if(theEvent == 'over') {
            if(!isSelected) {
                $('tab' + pkStrucId).addClassName('headerTabMo');
                if(Cookie.get('showTabTips')) {
                    $('tab' + pkStrucId).addClassName('headerTabMoTip');
                } else {
                    $('tab' + pkStrucId).addClassName('headerTabMo');
                }
                if(lastTabID && $(lastTabID) && lastTabID != 'tab' + pkStrucId) {
                    $(lastTabID).removeClassName('headerTabMo');
                    $(lastTabID).removeClassName('headerTabMoTip');
                }
                lastTabID = 'tab' + pkStrucId;
            } else {
                if(lastTabID && $(lastTabID) && lastTabID != 'tab' + pkStrucId) {
                    $(lastTabID).removeClassName('headerTabMo');
                    $(lastTabID).removeClassName('headerTabMoTip');
                }
            }
            if(Cookie.get('showTabTips')) {
                showTabBox('tt' + pkStrucId);
            }
        }
    }
}

function showTabBox(elemID) {
    if(elemID && $(elemID) && $('tabinfo') && $('tdAll') && $('headcell') && $('tblBodyContainer')) {
        
        $('tabinfo').innerHTML = $(elemID).innerHTML;
        $('tabinfo').style.display = 'block';
        //Effect.Appear($('tabinfo'), {duration: 2, from: 0.0, to: 1.0});
    }
}

function hideTabBox() {
    if($('tabinfo')) {
        // $('tabinfo').style.display = 'none';
    }
}

function addFeed(boolQuit) {
    if($('addFeed')) {
        if(boolQuit) {
            $('addFeed').style.display = 'none';
            if($('formRss') && $('formRss').strRssTitle && $('formRss').strRssURL) {
                $('formRss').strRssTitle.value = '';
                $('formRss').strRssURL.value = '';
            }
        } else {
            $('addFeed').style.display = 'block';
            if($('formRss') && $('formRss').strRssTitle) {
                $('formRss').strRssTitle.focus();
            }
        }
    }
}

function submitAjax(strFormID) {
    // Submits a complete form via AJAX.
    // Interprets response for instructions on what to do next.
    // Response should be JSON-encoded.
    //
    // Valid reponses include:
    // arrResponse.update               => array of divs to update
    // arrResponse.update.divID.html    => HTML contents to update divID
    // arrResponse.reload               => if true, reload current page
    // arrResponse.location             => if set, redirect to this web address
    // arrResponse.alerts               => array of alerts
    // arrResponse.alerts.[1,2,3...]    => each alert
    
    if(strFormID && $(strFormID)) {
        var arrFields = Form.getElements($(strFormID));
        if(arrFields.length > 0) {
            var arrPostData = new Array();
                arrPostData.push('autoajax=true');
            var arrAllFields = new Array();
            for(var i = 0; i < arrFields.length; i++) {
                // Loop through all non-disabled form elements and save them to arrFields array.
                if(!arrFields[i].disabled) {
                    arrPostData.push('arrFormFields[]=' + encodeURIComponent(arrFields[i].name));
                    switch(arrFields[i].type) {
                        case 'hidden':
                        case 'text':
                        case 'textarea':
                        case 'password':
                        case 'file':
                            arrPostData.push(encodeURIComponent(arrFields[i].name) + '=' + encodeURIComponent(arrFields[i].value));
                            break;
                        
                        case 'select-one':
                            if($(strFormID)[i].selectedIndex != 0) {
                                arrPostData.push(encodeURIComponent(arrFields[i].name) + '=' + encodeURIComponent(arrFields[i].value));
                            }
                            break;
                            
                        case 'select-multiple':
                            //$(strFormID)[i].selectedIndex = -1;
                            break;
                            
                        case 'checkbox':
                        case 'radio':
                            if($(strFormID)[i].checked == true) {
                                arrPostData.push(encodeURIComponent(arrFields[i].name) + '=' + encodeURIComponent(arrFields[i].value));
                            }
                            break;
                    }
                }
            }
            
            //arrPostData.push('arrFormFields=[' + arrAllFields.join('&') + ']');
            var postData = arrPostData.join('&');
            
            var handlerSubmitAjax = function(t) {
                strResponse = (t.responseText);
                var arrResponse = new Array();
                if(arrResponse = strResponse.evalJSON(true)) {
                    if(arrResponse.alerts && arrResponse.alerts.length > 0) {
                        for(var a = 0; a < arrResponse.alerts.length; a++) {
                            alert(arrResponse.alerts[a]);
                        }
                        
                        
                        
                        if(arrResponse.reload) {
                            alert('reloading page');
                            window.location.reload(true);
                        }
                    }
                }
            }
            
            var errSubmitAjax = function(t) {
                alert('Error ' + t.status + ' -- ' + t.statusText);
            }
        
            new Ajax.Request(strBasePath + 'ajax.php', {method:'post', postBody:postData, onSuccess:handlerSubmitAjax, onFailure:errSubmitAjax});
        }
    }
}

function doAddFeed() {
    if($('formRss') && $('formRss').strRssTitle && $('formRss').strRssURL) {
        if($('formRss').strRssTitle.value.length == 0) {
            alert("You must enter a title to add an RSS feed.");
            $('formRss').strRssTitle.focus();
            return;
        }
        if($('formRss').strRssURL.value.length == 0) {
            alert("You must enter a valid RSS Feed URL.");
            $('formRss').strRssURL.focus();
            return;
        }
        
        // No errors so far, try adding feed.
        var handlerFunc = function(t) {
            strResponse = (t.responseText);
            if(strResponse == 'PASS') {
                alert("Your RSS Feed has been added to your Custom Feeds.\nPlease click OK to refresh this page.");
                $('formRss').strRssTitle.value = '';
                $('formRss').strRssURL.value = '';
                window.location.reload(false);
            } else {
                var strError = '';
                if(strResponse.substr(0, 6) == 'FAIL: ') {
                    strError += '\n' + strResponse.substr(6);
                }
                alert('Unable to add RSS feed.' + strError);
                $('formRss').strRssURL.focus();
            }
        }
        
        var errFunc = function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
    
        var postData  = 'add=rssfeed';
            postData += '&strTitle=' + encodeURIComponent($('formRss').strRssTitle.value);
            postData += '&strRssURL=' + encodeURIComponent($('formRss').strRssURL.value);
        new Ajax.Request(strBasePath + 'ajax.php', {method:'post', postBody:postData, onSuccess:handlerFunc, onFailure:errFunc});
    }
}

function removeFeed(pkRssID) {
    if(pkRssID && confirm('Are you sure you want to remove this feed from your Custom Feeds?')) {
        var handlerFunc = function(t) {
            strResponse = (t.responseText);
            if(strResponse == 'PASS') {
                alert("The selected RSS Feed has been removed your Custom Feeds.\nPlease click OK to refresh this page.");
                $('formRss').strRssTitle.value = '';
                $('formRss').strRssURL.value = '';
                window.location.reload(false);
            } else {
                var strError = '';
                if(strResponse.substr(0, 6) == 'FAIL: ') {
                    strError += '\n' + strResponse.substr(6);
                }
                alert('Unable to remove RSS feed.' + strError);
            }
        }
        
        var errFunc = function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
    
        var postData  = 'remove=rssfeed';
            postData += '&pkRssID=' + encodeURIComponent(pkRssID);
        new Ajax.Request(strBasePath + 'ajax.php', {method:'post', postBody:postData, onSuccess:handlerFunc, onFailure:errFunc});
    }
}