var http;
var divname;
var alertOptions = {};

//----------------------------------------------------------------------
// Service wide javascript
//----------------------------------------------------------------------
$(document).ready(function() {

    // if the sidebar is empty.. hide it.
    hide_empty_sidebar();


    if(typeof $.fn.livequery == 'function'){
        // activate help links livequery
        // will automatically update links, even if they
        // are added using ajax
        $("a.tippable:not(.cluetip)").livequery(function() {
            $(this).cluetip({
                width: $(this).attr("cstyle") == "wide" ? 800 : 400,
                sticky: true,
                positionBy: 'bottomTop',
                closePosition: 'title',
                activation: 'click',
                arrows: true
            });
        });

        // format all numeric fields
        $(document).find("input.numeric:not(.inited)").livequery(function() {
            $(this).numeric({
                allow:"."
            }).bind("blur", function() {
                $(this).formatCurrency({
                    showZero: false
                });
            })
        });

        // format all alphanumeric fields
        $(document).find("input.alphanumeric:not(.inited)").livequery(function() {
            $(this).alphanumeric({
                allow:"_-",
                nocaps: true
            });
        });

        // format all percent fields
        $(document).find("input.percent:not(.inited)").livequery(function() {
            $(this).numeric({
                allow:"."
            }).bind("blur", function() {
                $(this).formatCurrency({
                    symbol: '',
                    showZero: false
                });
            })
        });

        // format all integer fields
        $(document).find("input.integer:not(.inited)").livequery(function() {
            $(this).numeric();
        });

        // force all the numeric fields to format their values
        $(document).find("input.numeric:not(.inited),input.integer:not(.inited),input.percent:not(.inited)").each(function() {
            $(this).addClass("inited");
            $(this).blur();
        });
    }
    if(typeof $.fn.autocomplete == 'function'){
        $("#tagsearch").autocomplete("/tagquery", {
            width: 320,
            max: 100,
            highlight: false,
            scroll: true,
            scrollHeight: 240,
            cacheLength: 10,
            multiple: false,
            extraParams : {
                refs: 1,
                zero: 1
            },
            formatItem: function(data, i, n, value) {
                return value.split(",")[0];
            },
            formatResult: function(data, value) {
                return value.split(",")[0];
            }
        });
    }

    // make sure the body is at least 500 pixels high
    var cpage = $("body");
    if (cpage.height() < 500) {
        cpage.css("height", "500px");
        cpage.css("overflow", "visible");
    }

    $(document).trigger("page.ready");
// and we're out 

});
//----------------------------------------------------------------------
function sprintf () {
    var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
    while (f) {
        if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
        else if (m = /^\x25{2}/.exec(f)) o.push('%');
        else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
            if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
            if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
                throw("Expecting number but found " + typeof(a));
            switch (m[7]) {
                case 'b':
                    a = a.toString(2);
                    break;
                case 'c':
                    a = String.fromCharCode(a);
                    break;
                case 'd':
                    a = parseInt(a);
                    break;
                case 'e':
                    a = m[6] ? a.toExponential(m[6]) : a.toExponential();
                    break;
                case 'f':
                    a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a);
                    break;
                case 'o':
                    a = a.toString(8);
                    break;
                case 's':
                    a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a);
                    break;
                case 'u':
                    a = Math.abs(a);
                    break;
                case 'x':
                    a = a.toString(16);
                    break;
                case 'X':
                    a = a.toString(16).toUpperCase();
                    break;
            }
            a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
            c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
            x = m[5] - String(a).length;
            p = m[5] ? str_repeat(c, x) : '';
            o.push(m[4] ? a + p : p + a);
        }
        else throw ("Huh ?!");
        f = f.substring(m[0].length);
    }
    return o.join('');
}
//----------------------------------------------------------------------
function hide_empty_sidebar(){
    var obj = $('#cside');
    if (obj && obj.html()) {
        if (obj.html().replace(/^\s+|\s+$/g,"") == ''){
            obj.css("display", "none");
            obj.width($('#pagetitle').width());
        }
    }
}

//----------------------------------------------------------------------
function extwrite(message) {
    document.write(message);
}
//----------------------------------------------------------------------
function createRequestObject() {
    var req = false;
    if (window.XMLHttpRequest) {
        // native XMLHttpRequest object
        try {
            req = new XMLHttpRequest();
        }
        catch (e) {
            req = false;
        }
    } else if (window.ActiveXObject) {
        // IE/Windows ActiveX version
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {
                req = false;
            }
        }
    }
    return req;
}
//----------------------------------------------------------------------
function replaceDiv_response() {
    if (http.readyState == 4){
        var response = http.responseText;
        $(divname).innerHTML = response;
    }
}
//----------------------------------------------------------------------
function replaceDiv(name, url) {
    divname = name;
    http = createRequestObject();
    http.onreadystatechange = replaceDiv_response;
    http.open('GET', url);
    http.send(null);
    return false;
}

//----------------------------------------------------------------------
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

//----------------------------------------------------------------------
function ltrim(stringToTrim) {
    return stringToTrim.replace(/^\s+/,"");
}

//----------------------------------------------------------------------
function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/,"");
}
//----------------------------------------------------------------------
function replace(value, from, to) {
    return value.replace(from,to);
}

//----------------------------------------------------------------------
function numeric_cleanup( value ) {
    return replace(value, /[^0-9\.]/, '');
}

//----------------------------------------------------------------------
// open a passive notification
//----------------------------------------------------------------------
function growl( settings ) {
    var options = {
        closer: false,
        check: 1000,
        life: 3000,
        theme: '',
        content: "No message provided"
    }

    // if passed a string, make options object
    if (typeof(settings) == "string") {
        options.content = settings;
    } else {
        // copy their settings into options
        for( var i in settings ) {
            options[i] = settings[i];
        }
    }

    $.jGrowl(
        options.content, {
            header: (options.title) ? options.title : '',
            closer: false,
            check: 1000,
            life: 3000,
            theme: options.theme
        }
        );
}
//----------------------------------------------------------------------
// open a passive notification
// {
//      save:       true | false,
//      close:      true | false,
//      onSave:     function
//      onClose:    function
//      content:    any content to show in the box
//      timeout:    # of ms to stay open before closing automatically
//      focusAfter: selector to pass focus to after close (requires timeout)
//
//       Note: if close and save buttons are hidden, footer hides
//       automatically unless footer is TRUE
//
//----------------------------------------------------------------------
function alertBox( settings ) {
    alertOptions = {
        confirm: false,
        overlay: true,		// show the curtain?
        opacity: 0.5,
        save: false,        // hide save button
        close: true,        // hide close button
        footer: false,      // hide footer
        klass: '',			// layout class that defines th size
        onConfirm: null,    // after-confirm event
        onSave: null,       // after-save event
        onClose: null,      // after-close event
        beforeReveal: null,	// before-open event
        timeout: 3000,      // timeout timer in milliseconds
        content: ''         // content to show
    }

    // if passed a string, make options object
    if (typeof(settings) == "string") {
        alertOptions.content = settings;
    } else {
        // copy their settings into options
        for( var i in settings ) {
            alertOptions[i] = settings[i];
        }
    }

    // ensure mutual exclusivity and save has
    // precedence over confirm
    if (alertOptions.save == true) {
        alertOptions.confirm = false;
    }

    // map our options into facebox
    $.extend($.facebox.settings, alertOptions);

    // handle reveal event
    $(document).bind('reveal.facebox', function() {
        // before show
        if (alertOptions.beforeReveal) {
            alertOptions.beforeReveal($("#facebox .content"));
        }

        // hide save?
        $("#facebox .save").css({
            display: (alertOptions.save) ? 'block' : 'none',
            visibility: (alertOptions.save) ? 'visible' : 'hidden'
        });
        // setup onsave event
        if (alertOptions.onSave) {
            $(document).unbind("save.facebox");
            $(document).bind('save.facebox', function() {
                if (alertOptions.onSave) {
                    alertOptions.onSave($("#facebox"));
                }
            });
        }

        // hide or show confirm
        $("#facebox .confirm").css({
            display: (alertOptions.confirm) ? 'block' : 'none',
            visibility: (alertOptions.confirm) ? 'visible' : 'hidden'
        });

        $(document).bind('confirm.facebox', function() {
            // remove the timer
            $(document).stopTime("alertTimeout");
            // optionally callback
            if (alertOptions.onConfirm) {
                alertOptions.onConfirm($("#facebox"));
            }
        });

        // hide close?
        $("#facebox .close").css({
            display: (alertOptions.close) ? 'block' : 'none',
            visibility: (alertOptions.close) ? 'visible' : 'hidden'
        });

        $(document).bind('close.facebox', function() {
            // remove the timer
            $(document).stopTime("alertTimeout");
            // optionally callback
            if (alertOptions.onClose) {
                alertOptions.onClose($("#facebox"));
            }
        });
        // hide footer
        if ((typeof(alertOptions.footer) == "undefined" || alertOptions.footer == false) &&
            (alertOptions.save == true || alertOptions.close == true)) {
            alertOptions.footer = true;
        }
		
        $("#facebox .footer").css({
            display: (alertOptions.footer) ? 'block' : 'none',
            visibility: (alertOptions.footer) ? 'visible' : 'hidden'
        });

        // if timeout is specified
        if (alertOptions.timeout !== false && alertOptions.timeout != null) {
            $(document).oneTime(parseInt(alertOptions.timeout), "alertTimeout", function() {
                // remove the timer
                $(document).stopTime("alertTimeout");
                // close the box
                $.facebox.close();
                // focus if asked to
                $(alertOptions.focusAfter).focus();
            });
        }
    });

    if (alertOptions.klass != "") {
        $.facebox(alertOptions.content, alertOptions.klass);
    } else {
        $.facebox(alertOptions.content);
    }
}
//----------------------------------------------------------------------
function searchTags( value ) {
    var newValue = replace(value, /"/g, '&quot;');
    newValue = replace(newValue, /'/g, '&squot;');

    VS_Ajax_Search.do_search({
        keywords: newValue
    }, {
        "content_type": "json",
        'onFinish' : function(response) {
            // clear the body
            if (response.status == "OK") {
                window.location = response.redirect_to;
            } else {
                alertBox({
                    content: response.message,
                    save: false,
                    timeout: null
                });
            }
        }
    });
}

//----------------------------------------------------------------------
function showLoader( parent, bshow ) {
    if ($("div#loader").length == 0) {
        alertBox("No loader control on this page.");
        return false;
    }

    if (bshow == true) {
        $(parent).prepend($("div#loader").clone());
        $(parent).find("div#loader").removeClass("hidden");
        $(parent).find("div#loader #image").each(function() {
            var width = $(parent).find("div#loader:first").width();
            var height = $(parent).find("div#loader:first").height();
            //var iwidth = $(this).find("div#loader #image").width();
            //var iheight = $(this).find("div#loader #image").height();
            $(this).css({
                left: (width / 4) + "px",
                top: (height / 4) + "px"
            });
            $(this).attr("width", Math.round(width / 2));
            $(this).attr("height", Math.round(height / 2));
        });
    } else {
        $(parent).find("div#loader").remove();
    }

    return false;
}

//----------------------------------------------------------------------
function myencode( val ) {
    var xx = val.replace(/\"/g, '\\\"');
    var xx = xx.replace(/(.)[\n\r]+/g, "$1<br/>");
    return xx;
}

//----------------------------------------------------------------------
function delay_keycheck( delay, target, container, callback ) {
    var name = target;
    if (!name) {
        alertBox({
            timeout: null,
            content: 'Fatal Error : A call to delay_keycheck was made on an input with no id!'
        });
    } else {
        name = name + "_delay_keycheck";
        $(document).stopTime(name);
        $(document).oneTime(delay, name, function() {
            showLoader(container, true);
            if (callback) {
                callback(target, container);
            }
        });
    }
}

//----------------------------------------------------------------------
function gotoURL( url ) {
    window.location.href = url;
    return false;
}

function switch_style ( css_title, style_cookie_name, style_cookie_duration ){
    var i, link_tag ;
    for (i = 0, link_tag = document.getElementsByTagName("link") ; i < link_tag.length ; i++ ) {
        if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) &&
            link_tag[i].title) {
            link_tag[i].disabled = true ;
            if (link_tag[i].title == css_title) {
                link_tag[i].disabled = false ;
            }
        }
        set_cookie( style_cookie_name, css_title, style_cookie_duration );
    }
}
function set_style_from_cookie(style_cookie_name, default_style, style_cookie_duration){
    var css_title = get_cookie( style_cookie_name );
    if (css_title && css_title.length) {
        switch_style( css_title, style_cookie_name, style_cookie_duration);
    } else {
        switch_style(default_style, style_cookie_name, style_cookie_duration);
    }
}

function set_cookie( name, value, expires, path, domain, secure ){
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

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

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function get_cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );
        

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        
        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}
function upgrade_plan(data){
    window.open('/members/reactivate/change_plan.htm?feature=' + data, '_blank');
}

