/// <reference name="MicrosoftAjax.js" />
/// <reference path="jquery-1.3.2-vsdoc2.js" />

//EICv3 - Focusnetworks Brasil
//Version: 0.9.0.1

var EICv3 = function() {

    var self = this;
    var zIndex = 10;
    //    this.showSuccess = function(open, message, closeAction) {

    //        var container = $('#showSuccess');
    //        var content, closeButton;

    //        self.showCurtain(open);

    //        if (open) {

    //            content = $('#showSuccessMessage');
    //            closeButton = $('#showSuccessLink');

    //            container.show().center();
    //            content.html(message);

    //            if (closeAction != undefined) {
    //                if (typeof (closeAction) == 'string') {
    //                    closeButton[0].href = closeAction;
    //                    closeButton[0].onclick = function() { };
    //                }
    //                else {
    //                    closeButton[0].href = '#';
    //                    closeButton[0].onclick = closeAction;
    //                }
    //            }
    //            else {
    //                closeButton[0].href = '#';
    //                closeButton[0].onclick = function() { return self.showSuccess(false); };
    //            }
    //        }
    //        else {
    //            container.hide();
    //        }

    //        return false;
    //    };
    //    this.showInformation = function(open, message, closeAction) {

    //        var container = $('#showInformation');
    //        var content, closeButton;

    //        self.showCurtain(open);

    //        if (open) {

    //            content = $('#showInformationMessage');
    //            closeButton = $('#showInformationLink');

    //            container.show().center();
    //            content.html(message);

    //            if (closeAction != undefined) {
    //                if (typeof (closeAction) == 'string') {
    //                    closeButton[0].href = closeAction;
    //                    closeButton[0].onclick = function() { };
    //                }
    //                else {
    //                    closeButton[0].href = '#';
    //                    closeButton[0].onclick = closeAction;
    //                }
    //            }
    //            else {
    //                closeButton[0].href = '#';
    //                closeButton[0].onclick = function() { return self.showSuccess(false); };
    //            }
    //        }
    //        else {
    //            container.hide();
    //        }

    //        return false;
    //    };
    //    this.showWarning = function(open, message, closeAction) {

    //        var container = $('#showWarning');
    //        var content, closeButton;

    //        self.showCurtain(open);

    //        if (open) {

    //            content = $('#showWarningMessage');
    //            closeButton = $('#showWarningLink');

    //            container.show().center();
    //            content.html(message);

    //            if (closeAction != undefined) {
    //                if (typeof (closeAction) == 'string') {
    //                    closeButton[0].href = closeAction;
    //                    closeButton[0].onclick = function() { };
    //                }
    //                else {
    //                    closeButton[0].href = '#';
    //                    closeButton[0].onclick = closeAction;
    //                }
    //            }
    //            else {
    //                closeButton[0].href = '#';
    //                closeButton[0].onclick = function() { return self.showSuccess(false); };
    //            }
    //        }
    //        else {
    //            container.hide();
    //        }

    //        return false;
    //    };
    this.alertDebug = function(message) {
        if (!$('#debugContainer')[0]) {
            $('body').prepend('<div id="debugContainer" style="position:fixed;top:170px;left:5px;z-index:1000;border:1px solid #00f;background:#fff;min-width:200px;min-height:110px;padding:5px;color:#000;"><span>Debug Window</span><a href="javascript:void[0];" onclick="$(this).parent().hide();eic.alertDebugClear();" style="position:absolute;top:2px;right:2px;color:#f00;font-weight:bold;">X</a><div id="debugContent" style="font-size:12px !important;"></div></div>');
        }

        $('#debugContainer').show();
        $('#debugContent').html($('#debugContent').html() + '<br />\n' + message);

        return false;
    };
    this.alertDebugClear = function() {
        if ($('#debugContent')[0]) {
            $('#debugContent').html('');
        }
        return false;
    };

    this.showCurtain = function(open) {

        if (!$('#curtain')[0]) {
            $('body').append('<iframe id="curtain" src="" frameborder="0" scrolling="no" style="display:none;"></iframe>');
        }

        if (open) {
            $('#curtain').css({ position: 'absolute', display: 'block', height: $(document).height(), border: 'none', left: '0px', top: '0px', width: '100%', backgroundColor: '#000', zIndex: zIndex, opacity: 0 }).fadeTo(200, 0.5);
        }
        else {
            $('#curtain').fadeTo(200, 0).hide();
        }

        return false;
    };

    this.loadJavaScript = function(url) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;

        $('head')[0].appendChild(script);
    };

    this.ajaxLoader = function(el, id, centerVertical) {

        id = id || 0;

        var width = el.outerWidth() > 0 ? el.outerWidth() + 'px' : '100%';
        var height = 48;

        if (centerVertical) {
            height = el.height() > 48 ? el.height() : 48;
        }
        
        el.html('<div class="loaderSWF" style="height:' + height + 'px;' + (centerVertical ? 'padding:' + ((height - 48) / 2) + 'px 0;' : '') + 'text-align:center;width:' + width + ';"><div id="loaderSWF' + id + '"></div></div>');

        var flashvars = {};
        var params = { wmode: 'transparent' };

        function loadswj() {
            if (typeof (swfobject) != 'undefined') {
                swfobject.embedSWF(RootUrl + 'layout/swf/load.swf', 'loaderSWF' + id, '48', '48', '9.0.0', RootUrl + 'layout/swf/expressInstall.swf', flashvars, params);
            }
            else {
                window.setTimeout(function() { loadswj(); }, 100);
            }
        }

        if (typeof (swfobject) == 'undefined') {
            this.loadJavaScript(RootUrl + 'js/swfobject.js');
        }

        loadswj();

        return el;
    };
};



jQuery.fn.center = function() {
    // Always return each...
    return this.each(function() {
        var t = $(this);

        // Set position to other than 'static' so element shrink-wraps and width/height is calculated properly
        t.css({ position: 'fixed' });

        // Why are there no jQuery.fn.outerWidth/Height:s?
        var w = t.width(),
                    h = t.height(),
                    lrPadding = parseInt(t.css('paddingLeft'), 10) + parseInt(t.css('paddingRight'), 10),
                    lrBorder = parseInt(t.css('borderLeftWidth'), 10) + parseInt(t.css('borderRightWidth'), 10),
                    tbPadding = parseInt(t.css('paddingTop'), 10) + parseInt(t.css('paddingBottom'), 10),
                    tbBorder = parseInt(t.css('borderTopWidth'), 10) + parseInt(t.css('borderBottomWidth'), 10),
                    leftMargin = (w + lrPadding + lrBorder) / 2;
        topMargin = (h + tbPadding + tbBorder) / 2;

        t.css({
            position: 'fixed',
            left: '50%',
            top: '50%',
            marginLeft: '-' + leftMargin + 'px',
            marginTop: '-' + topMargin + 'px',
            zIndex: '99'
        });

        if ($.browser.msie && $.browser.version == '6.0') {
            t.css({
                position: 'absolute',
                top: ($(window).height() / 2) - $(this).outerHeight() + $(window).scrollTop(),
                marginTop: 0
            });

            //top: ($(window).height() - $(this).outerHeight()) / 2 + $(window).scrollTop() - 200
        }
    });
};

/*
|------------------------------------------------------------------------------------------|
|           Função: centerImage                                                            |
|        Descrição: Centralizar imagens dentro de um elemento que tem overflow hidden      |
|  ======================================================================================= |
|           Criado: 21/01/2009 Karl Douglas Nordfelt                                       |
|       Modificado:                                                        				   |
|------------------------------------------------------------------------------------------|
*/
jQuery.fn.centerImage = function() {

    var setInCenter = function(el) {
        var right = 0;
        var bottom = 0;
        var parent = $(el).parent();
        var parentWidth = parent.outerWidth();
        var parentHeight = parent.outerHeight();

        if (el.width > parentWidth) {
            right = (el.width - parentWidth) / 2;
        }

        if (el.height > parentHeight) {
            bottom = (el.height - parentHeight) / 2;
        }
        else if (el.height != parentHeight) {
            bottom = parseInt('-' + ((parentHeight - el.height) / 2), 10);
        }

        if (right > 0 || bottom != 0) {
            $(el).css({ position: 'relative', right: right + 'px', bottom: bottom + 'px' });
        }
    };

    return this.each(function() {
        setInCenter(this);
        $(this).load(function() { setInCenter(this); });
    });
};
//Textarea maxlength
//Usage:    $('textarea').maxlength({ 'feedback' : '.charsLeft' });
//          $('textarea').maxlength({'words': true,'feedback': '.wordsLeft'});
//http://remysharp.com/2008/06/30/maxlength-plugin/
jQuery.fn.maxlength = function(settings) {

    if (typeof settings == 'string') {
        settings = { feedback: settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function length(el) {
        var parts = el.value;
        if (settings.words) {
            parts = el.value.length ? parts.split(/\s+/) : { length: 0 };
        }
        return parts.length;
    }

    return this.each(function() {
        var field = this,
    	$field = $(field),
    	$form = $(field.form),
    	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
    	$charsLeft = $form.find(settings.feedback);

        function limitCheck(event) {
            var len = length(this),
    	    exceeded = len >= limit,
    		code = event.keyCode;

            if (!exceeded) {
                return;
            }

            switch (code) {
                case 8:  // allow delete
                case 9:
                case 17:
                case 36: // and cursor keys
                case 35:
                case 37:
                case 38:
                case 39:
                case 40:
                case 46:
                case 65:
                    return;

                default:
                    return settings.words && code != 32 && code != 13 && len == limit;
            }
        }


        var updateCount = function() {
            var len = length(field),
        	diff = limit - len;
            $charsLeft.html(diff || "0");

            // truncation code
            if (settings.hardLimit && diff < 0) {
                field.value = settings.words ?
                // split by white space, capturing it in the result, then glue them back
        		field.value.split(/(\s+)/, (limit * 2) - 1).join('') :
        		field.value.substr(0, limit);

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }

        updateCount();
    });
};

jQuery.fn.maxlength.defaults = {
    useInput: false,
    hardLimit: true,
    feedback: '.charsLeft',
    words: false
};

/*
|------------------------------------------------------------------------------------------|
|     Function: onlyNumbers                                                                |
|  Description: Only accept numbers, delete, tab or backspace button in a textbox          |
|  ======================================================================================= |
|      Created: 16/12/2009 Karl Douglas Nordfelt                                           |
|      Altered:                                                        				       |
|------------------------------------------------------------------------------------------|
*/
jQuery.fn.onlyNumbers = function() {
    return $(this).keypress(function(e){
        return !(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && !(e.ctrlKey && (e.which == 99 || e.which == 118 || e.which == 120 || e.which == 121 || e.which == 122)));
    });
};
/*
|------------------------------------------------------------------------------------------|
|     Function: onlyPhoneNumbers                                                           |
|  Description: Only accept phone numbers like digits, (, ), +, -, space, delete,          |
|               tab or backspace button in a textbox.                                      |
|  ======================================================================================= |
|      Created: 16/12/2009 Karl Douglas Nordfelt                                           |
|      Altered:                                                        				       |
|------------------------------------------------------------------------------------------|
*/
jQuery.fn.onlyPhoneNumbers = function() {
    return $(this).keypress(function(e) {
        return !(e.which != 45 && e.which != 43 && e.which != 41 && e.which != 40 && e.which != 32 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && !(e.ctrlKey && (e.which == 99 || e.which == 118 || e.which == 120 || e.which == 121 || e.which == 122)));
    });
};

var eic = new EICv3();

jQuery.fn.ajaxLoader = function() {
    return this.each(function(i) { eic.ajaxLoader($(this), i); });
};

window.alert = function(txt) {
    eic.alertDebug(txt);
};
