﻿
/*
Carrega um Drop Down List. 
data         : Dados formatados em Json. Deve ser um array de objetos.
textField    : nome da propriedade do objeto Json que sera utilizada como texto.
valueField   : nome da propriedade do objeto Json que sera utilizada como value.
firstElement : obejto Json com o primeiro elemento da lista. Null para nao adicionar.
propriedades do firstElement (value, text e selected) Ex.:{value:"-1", text:"TODOS", selected:true } 
*/
(function($) {
    // jQuery plugin definition  
    $.fn.loadSelect = function(params) {
        // aplica defaults 
        if (typeof params == 'string') {
            params = { data: params, textField: "Text", valueField: "Value", selectedValue: null, firstElement: null };
        }
        params = $.extend({ data: "", textField: "Text", valueField: "Value", selectedValue: null, firstElement: null }, params);
        // percorre todos os nos
        this.each(function() {

            var $t = $(this);
            if ($t.attr('tagName') != 'SELECT') {
                alert('A funcao loadSelect deve ser usada somente em elementos html Select');
            } else {

                $t.attr('options').length = 0;
                if (params.firstElement != null) {
                    var options = $t.attr('options');
                    options[options.length] = new Option(params.firstElement.text, params.firstElement.value, true, params.firstElement.selected);
                }

                if (params.data != '') {
                    var obj = eval('(' + params.data + ')');
                    $(obj).each(function(i, item) {
                        var sId = eval('item.' + params.valueField);
                        var sText = eval('item.' + params.textField);
                        var options = $t.attr('options');
                        options[options.length] = new Option(sText, sId, true, ('' + params.selectedValue == sId));

                    });
                }

            }
        });
        return this;
    };
})(jQuery);





/*
Carrega o conteudo de um User Control em um Div
projeto         : String com o caminho relativo do projeto. Usado para completar a URL.
userControlPath : caminho relativo do user control. Utilizado pelo ASPX assim é valida a sintax '~/caminho/control.ascx' 
data            : dados que serão utilizados no usercontrol. enviado via Form.
complete        : funcao executado ao termino da execucao ajax. sempre executa, com sucesso ou erro.
*/
(function($) {
    $.fn.loadUserControl = function(params) {
        params = $.extend({ projeto: '', userControlPath: '', data: '', complete: null, type: 'POST' }, params);

        this.each(function() {
            var $t = $(this);

            if (typeof params.data != 'string') {
                if (params.data != null)
                    params.data = JSON.stringify(params.data);
                else
                    params.data = '';
            }
            if (params.data != '') {
                params.data = params.data.substring(0, params.data.length - 1);
                params.data += ',"sUserControlPath":"' + params.userControlPath + '"}';
            } else {
                params.data += '{"sUserControlPath":"' + params.userControlPath + '"}';
            }

            //alert(json_parse('{"alert":"sadsdas"}'));

            $.ajax({
                url: params.projeto + 'core/renderusercontrol.aspx',
                type: params.type,
                data: eval('(' + params.data + ')'),
                dataType: 'html',
                success: function(data) {
                    if (data.length > 512000) {
                        alert('Não é possivel carregar uma página com mais de 500 Kbytes.');
                        return;
                    }

                    //Adiciona os scriptse link no DOM da pagina que carrega o User Control.
                    //seleciona somente os scripts em arquivos. tag com src.
                    var headID = document.getElementsByTagName("head")[0];
                    var arr = data.match(/<script(.|\n|\t)*?script>/gi);
                    if (arr != null) {
                        for (var i = 0; i < arr.length; i++) {
                            if (arr[i].match(/<.*?src=.*?>/) != null) {
                                var sSrc = arr[i].match(/src=".*?"/)[0];
                                sSrc = sSrc.replace('src=', '').replace('"', '').replace('"', '');
                                var newScript = document.createElement('script');
                                newScript.type = 'text/javascript';
                                newScript.src = sSrc;
                                headID.appendChild(newScript);
                            }
                        }
                    }
                    var arr = data.match(/<link(.|\n|\t)*?>/gi);
                    if (arr != null) {
                        for (var i = 0; i < arr.length; i++) {

                            if (arr[i].match(/<.*?href=.*?>/) != null) {
                                var sHref = arr[i].match(/href=".*?"/)[0];
                                sHref = sHref.replace('href=', '').replace('"', '').replace('"', '');
                                var newLink = document.createElement('link');
                                newLink.rel = "stylesheet";
                                newLink.type = "text/css";
                                newLink.media = "all";
                                newLink.href = sHref;
                                headID.appendChild(newLink);
                            }
                        }
                    }

                    //Seta o ajaxSetup para GET. Pois o jQuery executa POST para os scripts do conteudo em data.
                    //Também guarda a atual configuração do ajax para setar novamente após a execução.
                    var typeAnterior = jQuery.extend(true, {}, jQuery.ajaxSettings, null).type;
                    $.ajaxSetup({
                        type: 'GET'
                    });

                    var jData = $(data);

                    //POG; Insere e remove elemento no DOM para execução dos scripts JavaScript. 
                    //     Pois quando capturado o conteudo mais a frente o jQuery elimina tudo entre <script> tags
                    var $div = $('<div></div>').hide().appendTo($t).html(data).remove();

                    // recupera o dados dentro do div e insere no DOM
                    var innerData = $(data).find("#RenderUserControlContainer").html();
                    $t.html(innerData);


                    //Retorna a configuracao do ajax.
                    $.ajaxSetup({
                        type: typeAnterior
                    });
                },
                complete: params.complete
            });
        });
        return this;
    };
})(jQuery);


/*
Retorna os valores que representam o texto de um checkbox separados por virgula. 
Retorna vazio caso nao haja nenhum checado.
*/
(function($) {
    $.fn.getCheckboxVal = function() {
        var sVals = '';
        var i = 0;
        jQuery(this).each(function() {
            if (this.checked) {
                sVals += jQuery(this).val() + ',';
            }
        });
        if (sVals != '') {
            sVals = sVals.substring(0, sVals.length - 1);
        }
        return sVals;
    };
})(jQuery);

/*
Retorna os valores do checkbox separados por virgula. 
Retorna vazio caso nao haja nenhum checado.
*/
(function($) {
    $.fn.getCheckboxText = function() {
        var sText = '';
        var i = 0;
        jQuery(this).each(function() {
            if (this.checked) {
                sText += jQuery(this).next('label').text() + ',';
            }
        });
        if (sText != '') {
            sText = sText.substring(0, sText.length - 1);
        }
        return sText;
    };
})(jQuery);


/*
Registra os valores padrao de todas as chamadas ajax via jQuery
*/
(function($) {
    $.ajaxSetupParadigma = function() {
        $.ajaxSetup({
            error: function(xhr, msg) {
                if (xhr.responseText.indexOf('Paradigma.Wbc.ClicBusiness.Core.AjaxProSessionException') > 0) {
                    document.location.href = PTA_sProjeto + 'defaultnetmarket.aspx';    
                } else if (xhr.status == 0) {
                    alert('Você está offline.\n Por favor verifique sua conexão.');
                } else if (xhr.status == 404) {
                    alert('Requested URL not found.');
                    alert(xhr.responseText)
                } else if (xhr.status == 500) {
                    alert('Internel Server Error.');
                    alert(xhr.responseText)
                } else if (msg == 'parsererror') {
                    //alert('Error.\nParsing JSON Request failed or AjaxPro method threw an exception.');
                } else if (msg == 'timeout') {
                    alert('Request Time out.');
                    alert(xhr.responseText)
                } else {
                    alert('Unknow Error.');
                    alert(xhr.responseText)
                }
            },
            dataFilter: function(data, dataType) {
                if (dataType == 'xml') {
                    return data;
                }
                if (data.indexOf('r.error = {"Message"') > 0) {
                    var sErro = data.substring(data.indexOf('{"Message"'), data.length);
                    var oErro = eval('(' + sErro + ')');
                    alert('Ocorreu um erro inesperado.' + '\n' + oErro.Message + '\n' + oErro.Type);
                    throw ('error');
                } else {
                    return data;
                }
            },
            type: "POST"
        });
    };
})(jQuery);


/*
Funcao que encapsula chamada de metodos AjaxPro.
Pode ser extendida adicionando qualquer propriedade na funcao .ajax.
Adiciona somente o parametro 'method' que corresponde ao nome do metodo AjaxPro.
*/
(function($) {
    $.invokeAjaxPro = function(params) {
        if (typeof (params.data) == 'object') {
            params.data = $.toJSON(params.data);
        }
        $.ajax({
            url: (params.url != "undefined")?params.url:PTA_AjaxProUrl,
            type: 'POST',
            data: params.data,
            dataType: params.dataType,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("AjaxPro-Method", params.method);
            },
            success: params.success
        });
    };
})(jQuery);



var json_parse = function() {

    // This is a function that can parse a JSON text, producing a JavaScript
    // data structure. It is a simple, recursive descent parser.

    // We are defining the function inside of another function to avoid creating
    // global variables.

    var at,     // The index of the current character
         ch,     // The current character
         escapee = {
             '"': '"',
             '\\': '\\',
             '/': '/',
             b: 'b',
             f: '\f',
             n: '\n',
             r: '\r',
             t: '\t'
         },
         text,

         error = function(m) {

             // Call error when something is wrong.

             throw {
                 name: 'SyntaxError',
                 message: m,
                 at: at,
                 text: text
             };
         },

         next = function(c) {

             // If a c parameter is provided, verify that it matches the current character.

             if (c && c !== ch) {
                 error("Expected '" + c + "' instead of '" + ch + "'");
             }

             // Get the next character. When there are no more characters,
             // return the empty string.

             ch = text.charAt(at);
             at += 1;
             return ch;
         },

         number = function() {

             // Parse a number value.

             var number,
                 string = '';

             if (ch === '-') {
                 string = '-';
                 next('-');
             }
             while (ch >= '0' && ch <= '9') {
                 string += ch;
                 next();
             }
             if (ch === '.') {
                 string += '.';
                 while (next() && ch >= '0' && ch <= '9') {
                     string += ch;
                 }
             }
             if (ch === 'e' || ch === 'E') {
                 string += ch;
                 next();
                 if (ch === '-' || ch === '+') {
                     string += ch;
                     next();
                 }
                 while (ch >= '0' && ch <= '9') {
                     string += ch;
                     next();
                 }
             }
             number = +string;
             if (isNaN(number)) {
                 error("Bad number");
             } else {
                 return number;
             }
         },

         string = function() {

             // Parse a string value.

             var hex,
                 i,
                 string = '',
                 uffff;

             // When parsing for string values, we must look for " and \ characters.

             if (ch === '"') {
                 while (next()) {
                     if (ch === '"') {
                         next();
                         return string;
                     } else if (ch === '\\') {
                         next();
                         if (ch === 'u') {
                             uffff = 0;
                             for (i = 0; i < 4; i += 1) {
                                 hex = parseInt(next(), 16);
                                 if (!isFinite(hex)) {
                                     break;
                                 }
                                 uffff = uffff * 16 + hex;
                             }
                             string += String.fromCharCode(uffff);
                         } else if (typeof escapee[ch] === 'string') {
                             string += escapee[ch];
                         } else {
                             break;
                         }
                     } else {
                         string += ch;
                     }
                 }
             }
             error("Bad string");
         },

         white = function() {

             // Skip whitespace.

             while (ch && ch <= ' ') {
                 next();
             }
         },

         word = function() {

             // true, false, or null.

             switch (ch) {
                 case 't':
                     next('t');
                     next('r');
                     next('u');
                     next('e');
                     return true;
                 case 'f':
                     next('f');
                     next('a');
                     next('l');
                     next('s');
                     next('e');
                     return false;
                 case 'n':
                     next('n');
                     next('u');
                     next('l');
                     next('l');
                     return null;
             }
             error("Unexpected '" + ch + "'");
         },

         value,  // Place holder for the value function.

         array = function() {

             // Parse an array value.

             var array = [];

             if (ch === '[') {
                 next('[');
                 white();
                 if (ch === ']') {
                     next(']');
                     return array;   // empty array
                 }
                 while (ch) {
                     array.push(value());
                     white();
                     if (ch === ']') {
                         next(']');
                         return array;
                     }
                     next(',');
                     white();
                 }
             }
             error("Bad array");
         },

         object = function() {

             // Parse an object value.

             var key,
                 object = {};

             if (ch === '{') {
                 next('{');
                 white();
                 if (ch === '}') {
                     next('}');
                     return object;   // empty object
                 }
                 while (ch) {
                     key = string();
                     white();
                     next(':');
                     object[key] = value();
                     white();
                     if (ch === '}') {
                         next('}');
                         return object;
                     }
                     next(',');
                     white();
                 }
             }
             error("Bad object");
         };

    value = function() {

        // Parse a JSON value. It could be an object, an array, a string, a number,
        // or a word.

        white();
        switch (ch) {
            case '{':
                return object();
            case '[':
                return array();
            case '"':
                return string();
            case '-':
                return number();
            default:
                return ch >= '0' && ch <= '9' ? number() : word();
        }
    };

    // Return the json_parse function. It will have access to all of the above
    // functions and variables.

    return function(source, reviver) {
        var result;

        text = source;
        at = 0;
        ch = ' ';
        result = value();
        white();
        if (ch) {
            error("Syntax error");
        }

        // If there is a reviver function, we recursively walk the new structure,
        // passing each name/value pair to the reviver function for possible
        // transformation, starting with a temporary boot object that holds the result
        // in an empty key. If there is not a reviver function, we simply return the
        // result.

        return typeof reviver === 'function' ?
             function walk(holder, key) {
                 var k, v, value = holder[key];
                 if (value && typeof value === 'object') {
                     for (k in value) {
                         if (Object.hasOwnProperty.call(value, k)) {
                             v = walk(value, k);
                             if (v !== undefined) {
                                 value[k] = v;
                             } else {
                                 delete value[k];
                             }
                         }
                     }
                 }
                 return reviver.call(holder, key, value);
             } ({ '': result }, '') : result;

    };
} ();
