var http;
var divname;
var alertOptions = {};
var oldTarget = null;
var alertUrl = '/members/disable_alert.htm?atype=jobalert';

//----------------------------------------------------------------------
function ele(eleName) {
    if (document.getElementById && document.getElementById(eleName)) {
        return document.getElementById(eleName);
    }
    else if (document.all && document.all(eleName)) {
        return document.all(eleName);
    }
    else if (document.layers && document.layers[eleName]) {
        return document.layers[eleName];
    }
    else {
        return false;
    }
}
//----------------------------------------------------------------------
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;
        ele(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 disableAlert(){
    jQuery('#alert').fadeOut();
    jQuery('#tfoot').css('padding-bottom',10)
    http = createRequestObject();
    http.open('GET', alertUrl);
    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 (typeof(value) == 'string') ? value.replace(from,to) : value;
}
 
//----------------------------------------------------------------------
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") {
        var text = settings;
        settings = { content: text };
    }

    // copy their settings into options
    $.extend(options, settings);

    // force the theme
    $.jGrowl.defaults.theme = options.theme;
    // and show the growl
    $.jGrowl(
        options.content, {
            header: (options.title) ? options.title : '',
            closer: false,
            check: 1000,
            life: 3000
        });
}

// return the next highest z-index
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>
    /// <param name="opt" type="object">
    /// inc: increment value,
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 1, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

//----------------------------------------------------------------------
// Tell is the parameter provided is numeric or not
//----------------------------------------------------------------------
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

//----------------------------------------------------------------------
// 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
//
//----------------------------------------------------------------------
$.alertDefaults = {
    overlay: true,		// show the curtain?
    opacity: 0.5,
    footer: true,       // hide footer
    klass: '',			// layout class that defines th size
    beforeReveal: null,	// before-open event
    afterReveal: null,  // after-open event
    timeout: false,      // timeout timer in milliseconds

    // close
    close: true,        // hide close button
    onClose: null,      // after-close event

    // save
    save: false,        // hide save button
    onSave: null,       // after-save event

    // confirmation
    confirm: false,
    onConfirm: null,    // after-confirm event
    onDecline: null,    // after-decline event

    // the stuff
    content: ''         // content to show
}

$.alertOptions = {};

function alertBox( settings ) {

	$.alertOptions = {
    	// close
    	close: true
	};

    // if passed a string, make options object
    if (typeof(settings) == "string") {
        $.alertOptions.content = settings;
    }

    // map our options into facebox
    $.extend($.alertOptions, $.alertDefault);
    $.extend($.alertOptions, settings);
    $.extend($.facebox.settings, $.alertOptions);

    // ensure content is wrapped
    if (replace($.alertOptions.content, "<p", "xx") == $.alertOptions.content) {
        $.alertOptions.content = "<p>" + $.alertOptions.content + "</p>";
    }

    // ensure mutual exclusivity and save has
    // precedence over confirm
    if ($.alertOptions.confirm == true) {
        $.alertOptions.onSave = null;
        $.alertOptions.onClose = null;
        $.alertOptions.save = false;
        $.alertOptions.close = false;
    }

    // handle reveal event
    $(document).unbind('reveal.facebox').bind('reveal.facebox', function() {
        // before show
        if ($.alertOptions.beforeReveal) {
            $.alertOptions.beforeReveal($("#facebox .content"));
        }

        // before show
        if ($.alertOptions.afterReveal) {
            $.alertOptions.afterReveal($("#facebox .content"));
        }

        // hide save?
        $("#facebox .save").css({
            display: ($.alertOptions.save) ? 'block' : 'none',
            visibility: ($.alertOptions.save) ? 'visible' : 'hidden'
        });
        
        function abSaveFacebox() {
            if ($.alertOptions.onSave) {
                $.alertOptions.onSave($("#facebox"));
            }
        }
        
        // setup onsave event
        if ($.alertOptions.onSave) {
            // remove the timer
            $(document).stopTime("alertTimeout");
            // remove the click
            $(document).unbind('save.facebox', abSaveFacebox).bind('save.facebox', abSaveFacebox);
        }

        // hide or show confirm
        $("#facebox").find(".confirm.confirm-yes,.confirm.confirm-no").each(function() {
            $(this).css({
                display: ($.alertOptions.confirm) ? 'block' : 'none',
                visibility: ($.alertOptions.confirm) ? 'visible' : 'hidden'
            });
        });

		function abDeclineFacebox() {
            // remove the timer
            $(document).stopTime("alertTimeout");
            // optionally callback
            if ($.alertOptions.onDecline) {
                $.alertOptions.onDecline($("#facebox"));
            }
		}

		function abConfirmFacebox() {
            // remove the timer
            $(document).stopTime("alertTimeout");
            // optionally callback
            if ($.alertOptions.onConfirm) {
                $.alertOptions.onConfirm($("#facebox"));
            }
		}

		function abCloseFacebox() {
            // remove the timer
            $(document).stopTime("alertTimeout");
            // optionally callback
            if ($.alertOptions.onClose) {
                $.alertOptions.onClose($("#facebox"));
            }
            
			// bindings
	        $(document).unbind('decline.facebox', abDeclineFacebox);
	        $(document).unbind('confirm.facebox', abConfirmFacebox);
            $(document).unbind('save.facebox', abSaveFacebox);
	        $(document).unbind('close.facebox', abCloseFacebox);
	        
	        $.alertOptions
	        
            // remove the facebox
			$("div#facebox").remove();
		}

		// bindings
        $(document).unbind('decline.facebox', abDeclineFacebox).bind('decline.facebox', abDeclineFacebox);
        $(document).unbind('confirm.facebox', abConfirmFacebox).bind('confirm.facebox', abConfirmFacebox);
        $(document).unbind('close.facebox', abCloseFacebox).bind('close.facebox', abCloseFacebox);

        // hide close?
        $("#facebox .close").css({
            display: ($.alertOptions.close) ? 'block' : 'none',
            visibility: ($.alertOptions.close) ? 'visible' : 'hidden'
        });

        
        // hide footer
        if ((typeof($.alertOptions.footer) == "undefined" || $.alertOptions.footer == false) &&
            ($.alertOptions.save == true || $.alertOptions.close == true || $.alertOptions.confirm == true)) {
            $.alertOptions.footer = true;
        }

        $("#facebox .footer").css({
            display: ($.alertOptions.footer) ? 'block' : 'none',
            visibility: ($.alertOptions.footer) ? 'visible' : 'hidden'
        });

        // remove the timer
        $(document).stopTime("alertTimeout");

        // if timeout is specified
        if (isNumber($.alertOptions.timeout)) {
            $(document).oneTime($.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 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());
        var loader = $(parent).find("div#loader:first");
        $(loader).find("img:first").each(function() {
            var width = parseInt($(this).css("width"));
            var height = parseInt($(this).css("height"));
            var xoffset = 0, yoffset = 0;
            if (width > $(parent).width()) {
                xoffset = 0 - (width - $(parent).width()) / 2;
            } else {
                xoffset = ($(parent).width() - width) / 2;
            }
            if (height > $(parent).height()) {
                yoffset = 0 - (height - $(parent).height()) / 2;
            } else {
                yoffset = ($(parent).height() - height) / 2;
            }
            $(loader).css({
                left: xoffset + "px",
                top: yoffset + "px"
            });
            $(loader).removeClass("hidden");
        })
    } 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() {
            if (container != null) {
                showLoader(container, true);
            }
            if (callback) {
		        $(document).stopTime(name);
                callback(target, container);
            }
        });
    }
}

//----------------------------------------------------------------------
function gotoURL( url ) {
    window.location.href = url;
    return false;
}

//----------------------------------------------------------------------
function str_repeat(i, m) {
    for (var o = []; m > 0; o[--m] = i);
    return(o.join(''));
}
//----------------------------------------------------------------------
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 audioFormat(text){

    var newText = text;
    var findreps = 
            '<span class="title ui-selectmenu-item-header stretch">$1 &mdash; $2</span>' +
            '<span class="duration ui-selectmenu-item-content">$3</span>' +
            '<span class="player ui-selectmenu-item-content" onmouseup="return handleEvent( event );" onmousedown="return handleEvent( event );" onclick="playAudio($1, this); return false;"></span>'+
            '<span class="clearer"></span>';

    newText = newText.replace(/^([^\|]+)\|([^\|]*)\|([0-9:]+)$/, findreps);

    return newText;
}
//----------------------------------------------------------------------
function videoFormat(text, login){
    var newText = text;
    var findreps = 
            '<span class="title ui-selectmenu-item-header stretch">$1 &mdash; $2</span>' +
            '<span class="vplayer ui-selectmenu-item-content" onmouseover="$(this).css("cursor", "pointer");" onmouseout="$(this).css("cursor", "default");"><div style="width: 120px; height: 68px;"><img src="$4" width="120" height="68" /></div></span>'+
            '<span class="clearer"></span>';
        
    newText = newText.replace(/^([^\|]+)\|([^\|]*)\|([0-9:]+)\|([^\|]*)\|([^\|]*)$/, findreps);

    return newText;
}
//----------------------------------------------------------------------
function handleEvent( event ) {
    if ($.browser.msie) {
        event.cancelBubble = true;
    } else {
        event.stopPropagation();
    }
    return false;
}
//----------------------------------------------------------------------
function playAudio( id, obj ) {
    var target = $(obj);
    showLoader( target, true );
    VS_Ajax_Sizzle.get_temp_audio_player({
        audio_id : id
    }, {
        "content_type": "json",
        'onFinish' : function(response){
            if (response.status == 'OK') {
            	if (oldTarget != null) {
            		$(oldTarget).html('');
            		$(oldTarget).css("background-image", "url(/images/icons/20x20/playbtn.png);");
            		oldTarget = null;
            	}
                //$(target).css("background-image", "none");
                $(target).html(response.code);
                //$(obj).find("object").trigger("click");
                oldTarget = target;
            }
            showLoader(target, false);
        }
    });
    return false;
}
//----------------------------------------------------------------------
function playVideo( id, obj, aspect ) {
    return false;
    var target = $(obj);
    showLoader( target, true );
    $("div.vs-video-wrapper").each(function() {
        //var parent = $(this).parent();
        $(this).remove();
    });
    VS_Ajax_Sizzle.get_temp_video_player({
        audio_id : id,
        width: 240,
        height: 68,
        aspect: aspect
    }, {
        "content_type": "json",
        'onFinish' : function(response){
            showLoader(target, false);
            if (response.status == 'OK') {
                alertBox({
                    content: response.code,
                    save: false,
                    confirm: false
                });
            }
        }
    });
    return false;
}
//----------------------------------------------------------------------
$(document).ready(function() {
    $("input.numeric").numeric();
    
    /*
    var height = $("div.wrapper div#content").innerHeight();
    height = (height > 620) ? "auto" : "620";
	$("div.wrapper div#content").css({
		"min-height": height + "px"
	});
    */
    try{
	    /*
	    $("form.qform").jqTransform({
	        skipElements: "select, textarea.custom"
	    });
	    */
    } catch(err){
    	alertBox( err );
    }
    
});

