﻿/// <reference path="third-party/jquery-1.5-vsdoc.js"/>

$(function () {
    $(".account-message").each(function () {
        var a = $("<a>").addClass("close");
        var div = $(this);
        a.click(function () {
            div.fadeOut("normal");
        });
        div.prepend(a);
    });
});

if (!window.Careers) window.Careers = {};

Careers.notify = function () {
    var numMsgs = 0;

    var appendMsg = function (json) {
        var html = '<div' + (json.id ? ' id="notify-' + json.id + '"' : '') + ' style="display:none">' +
            '<span class="notify-close"><a title="dismiss this notification">&times;</a></span>' +
                '<span class="notify-text">' + json.text + '</span></div>';

        var jDiv = $(html);

        jDiv.find('.notify-close').click(function () {
            close(json.id);
        });

        $("#notify-container").append(jDiv);
    };

    var close = function (messageId) {
        var jHide = $("#notify-" + messageId);
        var newMargin = 0;

        if (--numMsgs > 0) {
            newMargin = parseInt($("body").css("margin-top").match(/\d+/));
            newMargin = newMargin - (newMargin / (numMsgs + 1));
        }

        if (messageId > 0) {
            $.post("/messages/mark-as-read/" + messageId);
        }

        jHide.fadeOut("fast", function () {
            $("body").animate({ marginTop: newMargin + "px" }, 'fast', 'linear');
            jHide.remove();
        });
    };

    var lowerBody = function() {
        $("body").animate({ marginTop: "2.5em" }, 'fast', 'linear');
    };

    var show = function () {
        $('#notify-container div').fadeIn('slow');
    };

    return {
        showMessages: function (jsonMessageArray) {
            numMsgs = jsonMessageArray.length;
            for (var i = 0; i < numMsgs; i++) {
                appendMsg(jsonMessageArray[i]);
            }
            show();
        },
        show: function (html, id) {
            lowerBody();
            appendMsg({ text: html, id: id });
            show();
        },
        close: close
    };
} ();

var hideNotification = function () {
	var notification = $("#notify-container");
	notification.fadeOut("normal", function () {
		$("body").animate({ marginTop: "0" }, 'fast', 'linear');
	});
};


String.prototype.beginsWith = function (t, i) {
    if (i == false) {
        return (t == this.substring(0, t.length));
    } else {
        return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
    }
};

String.prototype.endsWith = function (t, i) {
    if (i == false) {
        return (t == this.substring(this.length - t.length));
    } else {
        return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase());
    }
};

String.prototype.contains = function (t) {
    return this.indexOf(t) > -1;
};

String.prototype.isEmailAddress = function () {
    var emailpattern = "^[0-9a-zA-Z\-\_\.\+]+@([0-9a-zA-Z\-]+[\.]{1})+[0-9a-zA-Z]+$";
    var emailregex = new RegExp(emailpattern, "i");
    return emailregex.test(this);
};

// encode arrays as "param" not "param[]", since the latter does not play nicely with ASP.NET
jQuery.ajaxSettings.traditional = true;

// from http://swip.codylindley.com
(function ($) {
    $.fn.popupWindow = function (instanceSettings) {
    
        $.fn.popupWindow.defaultSettings = {
            centerBrowser: 0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
            centerScreen: 0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
            height: 500, // sets the height in pixels of the window.
            left: 0, // left position when the window appears.
            location: 0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
            menubar: 0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
            resizable: 0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
            scrollbars: 0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
            status: 0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
            width: 500, // sets the width in pixels of the window.
            windowName: null, // name of window set from the name attribute of the element that invokes the click
            windowURL: null, // url used for the popup
            top: 0, // top position when the window appears.
            toolbar: 0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
        };

        settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});

        var windowFeatures = 'height=' + settings.height +
						',width=' + settings.width +
						',toolbar=' + settings.toolbar +
						',scrollbars=' + settings.scrollbars +
						',status=' + settings.status +
						',resizable=' + settings.resizable +
						',location=' + settings.location +
						',menuBar=' + settings.menubar;

        settings.windowName = this.name || settings.windowName;
        settings.windowURL = $(this).attr("href") || settings.windowURL;
        var centeredY, centeredX;

        if (settings.centerBrowser) {

            if ($.browser.msie) {//hacked together for IE browsers
                centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120) / 2) - (settings.height / 2)));
                centeredX = window.screenLeft + ((((document.body.offsetWidth + 20) / 2) - (settings.width / 2)));
            } else {
                centeredY = window.screenY + (((window.outerHeight / 2) - (settings.height / 2)));
                centeredX = window.screenX + (((window.outerWidth / 2) - (settings.width / 2)));
            }
            centeredY -= 30;
            window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
        } else if (settings.centerScreen) {
            centeredY = (screen.height - settings.height) / 2;
            centeredX = (screen.width - settings.width) / 2;
            window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
        } else {
            window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + settings.left + ',top=' + settings.top).focus();
        }
        return false;

    };
})(jQuery);


(function ($) {
    $.fn.scrollFix = function () {
        var el = $(this);

        if (el.offset()) {
        var doit = (el.outerHeight() + 100) < $(window).height();

            if (doit) {
                var top = el.offset().top;

                $(window).scroll(function () {
                    var isFixed = el.css("position") == "fixed";
                    var isPastTop = $(window).scrollTop() > top;
                    if (!isFixed && isPastTop) {
                        el.css("top", "10px").css("left", el.offset().left).css("position", "fixed");
                    } else if (isFixed && !isPastTop) {
                        el.css("top", "").css("left", "").css("position", "");
                    }
                });
            }
        }

        return $(this);
    };
})(jQuery);


(function ($) {
    $.fn.setProgress = function (text) {
        var el = $(this);

        if (el.is("input")){
            el.data("originalval", el.val()).css("min-width", el.outerWidth()).val(text).addClass("progress");
        } else if (el.is("a")) {
            el.data("originalval", el.html()).html(text).addClass("progress");
        }
        return $(this);
    };
})(jQuery);

(function ($) {
    $.fn.placeholder = function () {
        var test = document.createElement("input"), placeholderSupport = ("placeholder" in test);
        if (!placeholderSupport){
            $(this).each(function () {
                var field = $(this);
                var placeholder = field.attr("placeholder");

                field.attr("title", placeholder);
                var fldval = field.val();

                if (field.val() == '' && placeholder != '') {
                    field.val(placeholder).addClass("placeholder");
                }

                field.blur(function () {
                    if (field.val() == '') {
                        field.addClass("placeholder").val(field.attr("placeholder"));
                    }
                })
		        .focus(function () {
		            if (field.val() == field.attr("placeholder")) {
		                field.removeClass("placeholder").val("");
		            }
		        });

                field.focus().blur();

                var form = field.parents("form").eq(0);
                var formsubmits = form.find("input:submit"); 	// this is a hack, since the .submit event seems not to fire

                formsubmits.click(function () {
                    if (field.val() == placeholder)
                        field.val("");
                });

                form.submit(function () {
                    if (field.val() == placeholder)
                        field.val("");
                });
            });
        }
        return $(this);
    };
})(jQuery);


(function ($) {
    $.fn.fadeRemove = function () {
        var el = $(this);
        el.fadeOut(function () {
            $(this).remove();
        });
        return $(this);
    };
})(jQuery);

(function ($) {
    $.fn.isEmpty = function () {
        return $.trim($(this).val()).length == 0;
    };
})(jQuery);

(function ($) {
    $.fn.rememberAttr = function (name) {
        return $(this).data("original-" + name, $(this).attr(name));
    };
})(jQuery);

(function ($) {
    $.fn.restoreAttr = function (name) {
        return $(this).attr(name, $(this).data("original-" + name));
    };
})(jQuery);

(function ($) {
    $.fn.rememberVal = function () {
        return $(this).data("original-val", $(this).val());
    };
})(jQuery);

(function ($) {
    $.fn.restoreVal = function () {
        return $(this).val($(this).data("original-val"));
    };
})(jQuery);

(function ($) {
    $.fn.any = function (f) {
        return $(this).filter(f).length > 0;
    };
})(jQuery);


/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
* 
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/

// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.

(function ($, undefined) {
    '$:nomunge'; // Used by YUI compressor.

    $.fn.serializeObject = function () {
        var obj = {};

        $.each(this.serializeArray(), function (i, o) {
            var n = o.name,
        v = o.value;

            obj[n] = obj[n] === undefined ? v
          : $.isArray(obj[n]) ? obj[n].concat(v)
          : [obj[n], v];
        });

        return obj;
    };

})(jQuery);

String.prototype.truncate = function(maxLength, appendWhenTruncated) {
    var result = this.toString();

    if (maxLength && result.length > maxLength) {
        result = result.substr(0, maxLength) + appendWhenTruncated;
    }

    return result;
};

/*
console-shim 1.0.0
https://github.com/kayahr/console-shim
Copyright (C) 2011 Klaus Reimer <k@ailis.de>
Licensed under the MIT license
(See http://www.opensource.org/licenses/mit-license)
*/
(function () { function c(a, b) { return function () { a.apply(b, arguments) } } if (!window.console) window.console = {}; var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = function () { }; if (!a.debug) a.debug = a.log; if (!a.info) a.info = a.log; if (!a.warn) a.warn = a.log; if (!a.error) a.error = a.log })();

Careers.onEachLoad_ = [];

/**
* Register load scripts to be called onLoad and onPopState
*
* @param {Function} func
*            The function to call.
*/
Careers.onEachLoad = function (cb) {
    Careers.onEachLoad_.push(cb);
};
Careers.loaded_ = false;
Careers.load = function () {
    Careers.loaded_ = true;
    for (var i = 0, len = Careers.onEachLoad_.length; i < len; i++) {
        try {
            Careers.onEachLoad_[i]();
        }
        catch(e) {
            console.log("[ERROR] Careers.load: #" + i + ", :" + e);
        }
    }
};
Careers.loadOnce = function () {
    if (Careers.loaded_) return;
    Careers.load();
};

//StackExchange compatibility script layers
//Replicate StackExchange.debug.log calls:
Careers.debug = { log: window.console.log };
Careers.helpers = {};
Careers.options = { isMobile: false };

