// INIT
var nav = (document.layers);
var iex = (document.all);
var onloads = new Array();
var enablePops = true;
var trackBlocks = false;
var errors = 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();
    }

    // all ajax calls of type json will have their notices displayed using writeNotice.
    // if no writeNotice function is registered then no error will be thrown.
    jQuery(document).ajaxComplete(function(e, xhr, settings) {
        if (settings.dataType == 'json') {
            data = jQuery.parseJSON(xhr.responseText);
            // process notices
            if (data && data.notices) {
                // notices may contain notices or errors
                // and may or may not contain (but probably does) the notice_location
                writeNotice(data.notice_location||'top', data.notices);
            }

            if (data && data.redirect_url) {
                window.location.href = data.redirect_url;
                return false;
            }
        }
    });
});

/* -------------------- 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');
}


/* -------------------- 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));
    });
};

writeNotice = function(elem_id, notices) {
    if (jQuery('#'+elem_id).length) {
        if (notices.errors.length > 0) {
            jQuery('#' + elem_id).html(notices.errors[0]).removeClass('alert').addClass('error').addClass('show');
            errors = true;
        }
        if (notices.notices.length > 0) {
            jQuery('#' + elem_id).html(notices.notices[0]).removeClass('error').addClass('alert').addClass('show');
            errors = false;
        }
    } else {
        // convert notices into html so it can be show in the dialog. :P
        noticesHtml = makeNoticesHtml(notices);
        if (noticesHtml.length) {
            handleDialog(noticesHtml);
        }
    }
    jQuery('#loading_top').hide();
};

makeNoticesHtml = function(notices) {
    final_msgs = '';
    jQuery.each(notices, function(key, group) {
        msgs = '';
        var className = key==='notices'?'small_alert':'small_error';
        jQuery.each(group, function(index, message) {
            msgs += '<div class="'+className+'">'+message+'</div>';
        });
        final_msgs += msgs;
    });
    return final_msgs;
};


var d_timer, d_destroyer;
function handleDialog(data) {
    var loc;
    jQuery('#dialog').dialog('option', 'width', 'auto');
    if (data && data.length) {
        jQuery("#dialog").html(data);
        jQuery('#dialog').dialog('open');
        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' );
            }
        });

        var ajax_url = jQuery(this.elem).attr('href');
        var separator = -1 == ajax_url.indexOf('?') ? '?' : '&' ;
        ajax_url += separator + 'method=ajax';
        jQuery.ajax({
            cache: false,
            type: "GET",
            dataType: 'json',
            url: ajax_url,
            profile_actions: this, // the profileActionsManager function instance
            success: function(data, textStatus) {
                if (undefined===data.content) {
                    data.content = '';
                }
                data = jQuery.trim(data.content);
                // if a success handler was defined as a function we run it.
                // The registered success handler should do the stuff with the dialog if needed.
                if (typeof this.profile_actions.successHandler == 'function') {
                    this.profile_actions.successHandler.call(this, data, textStatus);
                // if no success handler then display a dialog
                } else if (data != "" && ! 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
                }
                // XXX: Formerly we would do both of those things.
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                var err_msg='';
                if (errorThrown) {
                    err_msg = " \n\rException: " + errorThrown;
                };
                jQuery('#dialog').dialog('close');
            },
            complete: function(XMLHttpRequest, textStatus) {
            }
        });
    }
}

