// INIT
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]();
    }
}

// On load...
jQuery(function() {
    // Show hidden elements on page load.
    jQuery('.show_on_load').removeClass('show_on_load');

    // Fancybox galleries
    jQuery("a[rel=gallery], a[rel=pgallery]").fancybox({titlePosition: 'inside'});

    var timestamps;
    if (timestamps = jQuery("abbr.timeago"), timestamps.length) {
        // Timeago timestamps
        timestamps.timeago();
    }
});

/* -------------------- Utility Functions -------------------- */
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 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 toDOM(HTMLstring) {
    var HTMLstring = jQuery("<div/>").html(HTMLstring).text();
    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) {
    jQuery(jQuery.isArray(messages) ? messages.join(', ') : messages).addClass(hide ? 'hide' : 'show').removeClass(hide ? 'show' : 'hide');
}

// 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 = (typeof response_text == "string" ?  string2xml(response_text) : response_text).getElementsByTagName('response'),
        r_status = parseInt(response_xml[0].getAttribute('status')),
        ldiv_id = response_xml[0].getAttribute('ldiv_id'),
        div_id = response_xml[0].getAttribute('div_id'),
        msg = response_xml[0].getAttribute('msg');
    
    jQuery('#' + div_id).html(msg).addClass(r_status ? 'alert' : 'error').removeClass(r_status ? 'error' : 'alert');
    show_hide('#' + ldiv_id, true);
    show_hide('#' + div_id, false);
    
    if (typeof(response_xml[0].childNodes[0]) !== 'undefined' && response_xml[0].childNodes[0] !== null) {
        return response_xml[0].childNodes[0].nodeValue;
    }
    else {
        return parseInt(r_status, 10);
    }
}

/* -------------------- Keys -------------------- */
function checkAllWatcher(id, cssexpr) {
    jQuery('#' + id).click(function() {
        jQuery(cssexpr).attr("checked", "checked");
        return false;
    });
}

function checkNoneWatcher(id, cssexpr) {
    jQuery('#' + id).click(function() {
        jQuery(cssexpr).attr("checked", "");
        return false;
    });
}

function confirmWatcher(cssexpr, msg, func) {
    jQuery(cssexpr).click(function() {
        if (msg.search(/{!/) != -1 && msg.search(/!}/) != -1) {
            msg1 = msg.replace(/{!replace_me!}/g, jQuery(this).attr("id").substring(18));
        }
        else {
            msg1 = msg;
        }

        if (!confirm(msg1)) {
            return false;
        }
        else if (func) {
            return func();
        }
    });
}

/* -------------------- Miscellaneous -------------------- */
// 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) {
    jQuery(window).load(function() {
        // check for dom elements that contain banner ads and set the src URL
        jQuery('#' + elem_id).attr('src', "http://" + url_params.ad_domain + "&pos=" + ad_pos + "&" + jQuery.param(url_params.query_str));
    });
};

var d_timer, d_destroyer;
function handleDialog(data) {
    var loc;
    if (loc = jQuery(data).find('redirect').text()) {
        window.location.assign(loc);
    }
    jQuery(".ui-dialog-content").html(data);
    jQuery('#dialog').dialog('option', 'width', 'auto');
    d_timer = setTimeout(function(){ jQuery('.ui-widget-content').fadeOut('slow'); }, 5000);
    d_destroyer = setTimeout(function(){ 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) {
                var loc;
                if (loc = jQuery(data).find('redirect').text()) {
                    window.location.assign(loc);
                    return false;
                }
                if (! jQuery(data).find('response').attr('status')) {
                        jQuery('#dialog').html(data);
                        jQuery('#dialog').dialog('open');
                        jQuery('#right_ad_box, #bottom_ad_box').hide(); // avoid flash zindex issue
                }
                // if a success handler was defined as a function 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) { }
        });
    }
}
