var nav = (document.layers);
var iex = (document.all);
var onloads = new Array();
var enablePops = true;
var trackBlocks = false;

function bodyOnLoad() {
    for (var i=0; i<onloads.length; i++) {
        onloads[i]();
    }
}

function dcHideLinks() {
  if (nav) {
    document.sitelinks.visibility = "hidden";
  } else {
    sitelinks.style.visibility = "hidden";
  }
} 

function dcHideLinksNav() {
  if (nav) {
    document.sitelinksnav.visibility = "hidden";
  }
  else {
    sitelinksnav.style.visibility = "hidden";
  }
}

function dcHideSearchLinksNav() {
    if (nav || document.searchlinksnav) {
    document.loadingImg.style.width = "138px";
    document.loadingImg.style.height = "25px";
    document.searchlinksnavImg.style.height = document.sitelinksnav.style.height;
        document.searchlinksnav.style.visibility = "hide";
    } else {
    loadingImg.style.width = "138px";
    loadingImg.style.height = "25px";
    searchlinksnavImg.style.height = searchlinksnav.style.height;
        searchlinksnav.style.display = "none";
    }
}

function popUrl(url, windowname, width, height, scrollbars, status) {
    if (status != "yes") {
        status = "no";
    }
    var screenwidth = screen.availWidth - 10;
    var screenheight = screen.availHeight - 30;
    var xpos = (screenwidth / 2) - (width / 2);
    var ypos = (screenheight / 2) - (height / 2);
    window.open(url, windowname, "width=" + width + ",height=" + height + ",top=" + xpos + ",left=" + ypos + ",status=" + status + ",scrollbars=" + scrollbars + ",resizable");
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function doSearchSN(action) {
    var elem_username = $('c_screenname');
    if (action == "clear") { 
        if (elem_username.value == "screenname") {
            elem_username.value = "";
            elem_username.focus();
        }
    }
    if (action == "reset") {
        if (elem_username.value == "") {
            elem_username.value = "screenname";
        }
    }
    if (action == "go") {
        if (validateUsername(elem_username) && (elem_username.value != "" && elem_username.value != "screenname")) {
            dcHideSearchLinksNav();
            document.search_sn_form.submit();
        }
    }
}

function string2xml(text) {
    // IE
    if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(text);
    }
    // real browsers
    else {
        var doc = new DOMParser().parseFromString(text, 'text/xml');
    }
    return doc.documentElement;
}

function checkAllWatcher(id, cssexpr) {
    Event.observe($(id), 'click', function(e) {
        $$(cssexpr).each(function(obj) { obj.checked = true; });
        Event.stop(e);
    });
}

function checkNoneWatcher(id, cssexpr) {
    Event.observe($(id), 'click', function(e) {
        $$(cssexpr).each(function(obj) { obj.checked = false; });
        Event.stop(e);
    });
}

function confirmWatcher(cssexpr, msg, func) {
    $$(cssexpr).each(
        function(element) {
            Event.observe(element, 'click', function(e) {
                if (msg.search(/{!/) != -1 && msg.search(/!}/) != -1) {
                    msg1 = msg.replace(/{!replace_me!}/g, Event.element(e).id.substring(18));
                }
                else {
                    msg1 = msg;
                }

                if (!confirm(msg1)) {
                    Event.stop(e);
                }
                else if (func) {
                    func();
                }
            });
        }
    );
}

function toDOM(HTMLstring) {
    var d = document.createElement('div');
    d.innerHTML = HTMLstring;
    var docFrag = document.createDocumentFragment();
    while (d.firstChild) {
        docFrag.appendChild(d.firstChild)
    };
    return docFrag;
} 

function show_hide(messages, hide) {
    if (messages.length > 0) {
        var i = 0;
        while (i < messages.length) {
            if ($(messages[i])) {
                if (hide) {
                    $(messages[i]).removeClassName('show');
                    $(messages[i]).addClassName('hide');
                } else {
                    $(messages[i]).removeClassName('hide');
                    $(messages[i]).addClassName('show');
                }
            }
            i++;
        }
    }
}

// sets the appropriate css class' and message for notices/alerts to the user on
// ajax response
// input: xml: <events><response status="0 OR 1 (SUCCESS OR FAIL)" ldiv_id="DIV
// ID OF LOADING... DIV" div_id="DIV ID OF MSG TO SHOW" msg="MESSAGE TO DISPLAY
// IN DIV">OPTIONAL RESPONSE VALUE</response></events>');
// return: if value exits return value else return status
//
function ajax_response_msg(response_text) {
    var response_xml = string2xml(response_text).getElementsByTagName('response');
    var r_status = response_xml[0].getAttribute('status');
    var ldiv_id = response_xml[0].getAttribute('ldiv_id');
    var div_id = response_xml[0].getAttribute('div_id');
    var msg = response_xml[0].getAttribute('msg');
    if ($(ldiv_id)) {
        $(ldiv_id).removeClassName('show');
        $(ldiv_id).addClassName('hide');
    }
    if ($(div_id)) {
        $(div_id).innerHTML = msg;
        if (r_status > 0) {
            $(div_id).removeClassName('error');
            $(div_id).addClassName('alert');
        } else {
            $(div_id).removeClassName('alert');
            $(div_id).addClassName('error');
        }
        $(div_id).removeClassName('hide');
        $(div_id).addClassName('show');
    }
    if (typeof(response_xml[0].childNodes[0]) != 'undefined' && response_xml[0].childNodes[0] != null) {
        return response_xml[0].childNodes[0].nodeValue;
    } else {
        return r_status;
    }
}

function validateUsername(element) {
    if (element.value == "") {
        alert('Please enter a username.');
        return false;
    }
    /* check that username is between 3 and 15 characters long */
    if (element.value.length < 3 || element.value.length > 15) {
        alert('Username must be between 3 and 15 characters.');
        return false;
    }

    /* check that username is only alphanumeric characters */
    if ( !/^[\w-]+$/i.test(element.value) ) {
        alert('Username can only contain alphanumeric characters.');
        return false;
    }
    return true;
}

// method to take an object of key:value pairs
// loop and build a string for url querystring: key=value
function buildQueryString(obj){
    var query_str = '';
    for (prop in obj) {
        query_str += encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) + "&";
    }

    // trim trailing ampersand &
    if (query_str.substring(query_str.length - 1) == "&") {
        query_str = query_str.substring(0, query_str.length - 1);
    }
    return query_str;
}

// check for DOM element holding banner add and build URL for it
// put in window load event to delay getting banners until site has fully loaded
writeBannerUrl = function(elem_id, ad_pos, url_params) {
    Event.observe(window, 'load', function(){
        //  build query string for 'demographic' info
        var url_query_str = buildQueryString(url_params.query_str);
        /**
         * check for dom elements that contain banner ads and set the src URL
         */
        if ($(elem_id)) {
            $(elem_id).writeAttribute('src', "http://" + url_params.ad_domain + "&pos=" + ad_pos + "&" + url_query_str);
        }
    });
}

var d_timer, d_destroyer;
function handleDialog(data) {
    if (jQuery(data).find('redirect').text()) {
        window.location = jQuery(data).find('redirect').text();
    }
    jQuery(".ui-dialog-content").html(data);
    jQuery('#dialog').dialog('option', 'width', 'auto');
    d_timer = setTimeout("jQuery('.ui-widget-content').fadeOut('slow');", 5000);
    d_destroyer = setTimeout("jQuery('#dialog').dialog('close');", 5500);
}

function profileActionsManager(dom_elem) {
    this.elem = dom_elem; // the document element clicked
    this.status;
    this.successHandler;

    this.handle = function() {
               jQuery('#dialog').dialog({
               bgiframe: false,
               autoOpen: false,
               width: 700,
               modal: true,
               draggable: false,
               resizable: false,
               close: function(event, ui) { jQuery('#right_ad_box, #bottom_ad_box').show(); clearTimeout(d_timer); clearTimeout(d_destroyer); jQuery('#dialog').dialog( 'destroy' );}
            });
        jQuery.ajax({
            cache: false,
            type: "GET",
            url: jQuery(this.elem).attr('href'),
            success: function(data, textStatus) {
                if('' != jQuery(data).find('redirect').text()) {
                    window.location = jQuery(data).find('redirect').text();
                    return false;
                }
                if (! jQuery(data).find('response').attr('status')) {
                        jQuery('#dialog').html(data);
                        var wdth = jQuery('.ui-dialog').width();
                        jQuery('#dialog').dialog('option', 'width', wdth);
                        jQuery('#dialog').dialog('open');
                        jQuery('#right_ad_box, #bottom_ad_box').hide(); // avoid flash zindex issue
                }
                // if a success handler was defined as a funciton we run it
                if (typeof profile_actions.successHandler == 'function') { profile_actions.successHandler.call(); }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { var err_msg=''; if (errorThrown) {err_msg = " \n\rException: " + errorThrown; }; alert('An error occurred: ' + textStatus + err_msg); jQuery('#dialog').dialog('close');},
            complete: function(XMLHttpRequest, textStatus) { }
            });
    }
}