/// <reference path="jquery.intellisense.js"/>

var messageErrorAcessServer = "N&atilde;o foi poss&iacute;vel acessar o serviço.";

/*Simple Color picker*/
(function ($) {
    $.fn.colorPicker = function ($$options) {
        // Defaults
        var $defaults = {
            color: new Array(
    "#000000", "#FFFFFF", "#EEEEEE", "#FFFF88", "#FF7400", "#6BBA70",
    "#006E2E", "#4096EE", "#356AA0"
    ),
            defaultColor: 0,
            columns: 0,
            click: function ($color) { }
        };

        var $settings = $.extend({}, $defaults, $$options);

        // Iterate and reformat each matched element
        return this.each(function () {
            var $this = $(this);
            // build element specific options
            var o = $.meta ? $.extend({}, $settings, $this.data()) : $settings;
            var $$oldIndex = typeof (o.defaultColor) == 'number' ? o.defaultColor : -1;

            var _html = "";
            for (i = 0; i < o.color.length; i++) {
                _html += '<div style="background-color:' + o.color[i] + ';"></div>';
                if ($$oldIndex == -1 && o.defaultColor == o.color[i]) $$oldIndex = i;
            }

            $this.html('<div class="jColorSelect">' + _html + '</div>');
            var $color = $this.children('.jColorSelect').children('div');
            // Set container width
            var w = ($color.width() + 2 + 2) * (o.columns > 0 ? o.columns : o.color.length);
            $this.children('.jColorSelect').css('width', w);

            // Subscribe to click event of each color box
            $color.each(function (i) {
                $(this).click(function () {
                    if ($$oldIndex == i) return;
                    if ($$oldIndex > -1) {
                        cell = $color.eq($$oldIndex);
                        if (cell.hasClass('check')) cell.removeClass(
          'check').removeClass('checkwht').removeClass('checkblk');
                    }
                    // Keep index
                    $$oldIndex = i;
                    $(this).addClass('check').addClass(isdark(o.color[i]) ? 'checkwht' : 'checkblk');
                    // Trigger user event
                    o.click(o.color[i]);
                });
            });

            // Simulate click for defaultColor
            _tmp = $$oldIndex;
            $$oldIndex = -1;
            $color.eq(_tmp).trigger('click');
        });
        return this;
    };


})(jQuery);

/*
*
* Copyright (c) 2006-2011 Sam Collett (http://www.texotela.co.uk)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* 
* Version 1.3
* Demo: http://www.texotela.co.uk/code/jquery/numeric/
*
*/
(function ($) {
    /*
    * Allows only valid characters to be entered into input boxes.
    * Note: fixes value when pasting via Ctrl+V, but not when using the mouse to paste
    *      side-effect: Ctrl+A does not work, though you can still use the mouse to select (or double-click to select all)
    *
    * @name     numeric
    * @param    config      { decimal : "." , negative : true }
    * @param    callback     A function that runs if the number is not valid (fires onblur)
    * @author   Sam Collett (http://www.texotela.co.uk)
    * @example  $(".numeric").numeric();
    * @example  $(".numeric").numeric(","); // use , as separater
    * @example  $(".numeric").numeric({ decimal : "," }); // use , as separator
    * @example  $(".numeric").numeric({ negative : false }); // do not allow negative values
    * @example  $(".numeric").numeric(null, callback); // use default values, pass on the 'callback' function
    *
    */
    $.fn.numeric = function (config, callback) {
        if (typeof config === 'boolean') {
            config = { decimal: config };
        }
        config = config || {};
        // if config.negative undefined, set to true (default is to allow negative numbers)
        if (typeof config.negative == "undefined") config.negative = true;
        // set decimal point
        var decimal = (config.decimal === false) ? "" : config.decimal || ".";
        // allow negatives
        var negative = (config.negative === true) ? true : false;
        // callback function
        var callback = typeof callback == "function" ? callback : function () { };
        // set data and methods
        return this.data("numeric.decimal", decimal).data("numeric.negative", negative).data("numeric.callback", callback).keypress($.fn.numeric.keypress).keyup($.fn.numeric.keyup).blur($.fn.numeric.blur);
    }

    $.fn.numeric.keypress = function (e) {
        // get decimal character and determine if negatives are allowed
        var decimal = $.data(this, "numeric.decimal");
        var negative = $.data(this, "numeric.negative");
        // get the key that was pressed
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        // allow enter/return key (only when in an input box)
        if (key == 13 && this.nodeName.toLowerCase() == "input") {
            return true;
        }
        else if (key == 13) {
            return false;
        }
        var allow = false;
        // allow Ctrl+A
        if ((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
        // allow Ctrl+X (cut)
        if ((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
        // allow Ctrl+C (copy)
        if ((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
        // allow Ctrl+Z (undo)
        if ((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
        // allow or deny Ctrl+V (paste), Shift+Ins
        if ((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
	|| (e.shiftKey && key == 45)) return true;
        // if a number was not pressed
        if (key < 48 || key > 57) {
            /* '-' only allowed at start and if negative numbers allowed */
            if (this.value.indexOf("-") != 0 && negative && key == 45 && (this.value.length == 0 || ($.fn.getSelectionStart(this)) == 0)) return true;
            /* only one decimal separator allowed */
            if (decimal && key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) {
                allow = false;
            }
            // check for other keys that have special purposes
            if (
			key != 8 /* backspace */ &&
			key != 9 /* tab */ &&
			key != 13 /* enter */ &&
			key != 35 /* end */ &&
			key != 36 /* home */ &&
			key != 37 /* left */ &&
			key != 39 /* right */ &&
			key != 46 /* del */
		) {
                allow = false;
            }
            else {
                // for detecting special keys (listed above)
                // IE does not support 'charCode' and ignores them in keypress anyway
                if (typeof e.charCode != "undefined") {
                    // special keys have 'keyCode' and 'which' the same (e.g. backspace)
                    if (e.keyCode == e.which && e.which != 0) {
                        allow = true;
                        // . and delete share the same code, don't allow . (will be set to true later if it is the decimal point)
                        if (e.which == 46) allow = false;
                    }
                    // or keyCode != 0 and 'charCode'/'which' = 0
                    else if (e.keyCode != 0 && e.charCode == 0 && e.which == 0) {
                        allow = true;
                    }
                }
            }
            // if key pressed is the decimal and it is not already in the field
            if (decimal && key == decimal.charCodeAt(0)) {
                if (this.value.indexOf(decimal) == -1) {
                    allow = true;
                }
                else {
                    allow = false;
                }
            }
        }
        else {
            allow = true;
        }
        return allow;
    }

    $.fn.numeric.keyup = function (e) {
        var val = this.value;
        if (val.length > 0) {
            // get carat (cursor) position
            var carat = $.fn.getSelectionStart(this);
            // get decimal character and determine if negatives are allowed
            var decimal = $.data(this, "numeric.decimal");
            var negative = $.data(this, "numeric.negative");

            // prepend a 0 if necessary
            if (decimal != "") {
                // find decimal point
                var dot = val.indexOf(decimal);
                // if dot at start, add 0 before
                if (dot == 0) {
                    this.value = "0" + val;
                }
                // if dot at position 1, check if there is a - symbol before it
                if (dot == 1 && val.charAt(0) == "-") {
                    this.value = "-0" + val.substring(1);
                }
                val = this.value;
            }

            // if pasted in, only allow the following characters
            var validChars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '-', decimal];
            // get length of the value (to loop through)
            var length = val.length;
            // loop backwards (to prevent going out of bounds)
            for (var i = length - 1; i >= 0; i--) {
                var ch = val.charAt(i);
                // remove '-' if it is in the wrong place
                if (i != 0 && ch == "-") {
                    val = val.substring(0, i) + val.substring(i + 1);
                }
                // remove character if it is at the start, a '-' and negatives aren't allowed
                else if (i == 0 && !negative && ch == "-") {
                    val = val.substring(1);
                }
                var validChar = false;
                // loop through validChars
                for (var j = 0; j < validChars.length; j++) {
                    // if it is valid, break out the loop
                    if (ch == validChars[j]) {
                        validChar = true;
                        break;
                    }
                }
                // if not a valid character, or a space, remove
                if (!validChar || ch == " ") {
                    val = val.substring(0, i) + val.substring(i + 1);
                }
            }
            // remove extra decimal characters
            var firstDecimal = val.indexOf(decimal);
            if (firstDecimal > 0) {
                for (var i = length - 1; i > firstDecimal; i--) {
                    var ch = val.charAt(i);
                    // remove decimal character
                    if (ch == decimal) {
                        val = val.substring(0, i) + val.substring(i + 1);
                    }
                }
            }
            // set the value and prevent the cursor moving to the end
            this.value = val;
            $.fn.setSelection(this, carat);
        }
    }

    $.fn.numeric.blur = function () {
        var decimal = $.data(this, "numeric.decimal");
        var callback = $.data(this, "numeric.callback");
        var val = this.value;
        if (val != "") {
            var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
            if (!re.exec(val)) {
                callback.apply(this);
            }
        }
    }

    $.fn.removeNumeric = function () {
        return this.data("numeric.decimal", null).data("numeric.negative", null).data("numeric.callback", null).unbind("keypress", $.fn.numeric.keypress).unbind("blur", $.fn.numeric.blur);
    }

    // Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini <dperini@nwbox.com>)
    $.fn.getSelectionStart = function (o) {
        if (o.createTextRange) {
            var r = document.selection.createRange().duplicate();
            r.moveEnd('character', o.value.length);
            if (r.text == '') return o.value.length;
            return o.value.lastIndexOf(r.text);
        } else return o.selectionStart;
    }

    // set the selection, o is the object (input), p is the position ([start, end] or just start)
    $.fn.setSelection = function (o, p) {
        // if p is number, start and end are the same
        if (typeof p == "number") p = [p, p];
        // only set if p is an array of length 2
        if (p && p.constructor == Array && p.length == 2) {
            if (o.createTextRange) {
                var r = o.createTextRange();
                r.collapse(true);
                r.moveStart('character', p[0]);
                r.moveEnd('character', p[1]);
                r.select();
            }
            else if (o.setSelectionRange) {
                o.focus();
                o.setSelectionRange(p[0], p[1]);
            }
        }
    }

})(jQuery);

/**
* Return true if color is dark, false otherwise.
* (C) 2008 Syronex / J.M. Rosengard
**/
function isdark(color) {
    var colr = parseInt(color.substr(1), 16);
    return (colr >>> 16) // R
    + ((colr >>> 8) & 0x00ff) // G 
    + (colr & 0x0000ff) // B
    < 500;
}

/*
* 	Character Count Plugin - jQuery plugin
* 	Dynamic character count for text areas and input fields
*	written by Alen Grakalic	
*	http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
*
*	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
*	Dual licensed under the MIT (MIT-LICENSE.txt)
*	and GPL (GPL-LICENSE.txt) licenses.
*
*	Built for jQuery library
*	http://jquery.com
*
*/

(function ($) {

    $.fn.charCount = function (options) {

        // default configuration properties
        var defaults = {
            allowed: 140,
            warning: 25,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj) {
            var count = $(obj).val().length;
            var available = options.allowed - count;
            if (available <= options.warning && available >= 0) {
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if (available < 0) {
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
            }
            $(obj).next().html(options.counterText + available);
        };

        this.each(function () {
            $(this).after('<' + options.counterElement + ' class="' + options.css + '">' + options.counterText + '</' + options.counterElement + '>');
            calculate(this);
            $(this).keyup(function () { calculate(this) });
            $(this).change(function () { calculate(this) });
        });

    };

})(jQuery);

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
Top Message Plugin
Copyright (c) 2009-2009 Takenet
Version: 1.0.0
    
Add this css code:
    
#pnlMessage{left:0;	position: fixed; text-align: center;	z-index: 9999; top: 0px; padding: 15px;	width: 100%;}
#pnlMessage span {font-weight: bold;	text-align: center;	text-indent: 0;	position: relative;	font-weight: bold; font-size:13px;}
.aCloseMessage{	float:right; margin-right:20px; text-decoration: none;}
.pnlSuccess{ background-color: #92A93F; color: #000000;}
.pnlFail{ background-color: #ba2c22; color: #000000; }
.pnlAlert {background-color:#fffee6; color:#000000; }
.pnlSuccess span{ color: #FFFFFF;}
.pnlFail span{color: #FFFFFF;}
.pnlAlert span{	color: #000000;	}
.pnlAlert .aCloseMessage {color:#000000; }
.pnlFail .aCloseMessage {color:#ffffff; }
.pnlSuccess .aCloseMessage {color:#ffffff; }
*/
function ShowMessage(type, message) {
    var aux;
    $("#pnlMessage").html("");
    $("#pnlMessage.pnlSuccess").remove();
    $("#pnlMessage.pnlAlert").remove();
    $("#pnlMessage.pnlFail").remove();
    switch (type) {
        case "alert":
            aux = "<div id='pnlMessage' class='pnlAlert' style='display:none'>";
            break;
        case "success":
            aux = "<div id='pnlMessage' class='pnlSuccess' style='display:none'>";
            break;
        case "fail":
            aux = "<div id='pnlMessage' class='pnlFail' style='display:none'>";
        default:
            break;
    }
    aux += "<span id='spnMessage'>" + message + "</span>";
    aux += "<a href='javascript:void(null)' onclick='CloseMessage1()' id='lnkCloseMessage' class='aCloseMessage'>[X]</a></div>";
    return aux;
}

function CloseMessage1() {
    $("#pnlMessage").slideUp("slow");
}

function CloseMessageStatus() {
    $(".pnlSuccess").slideUp("slow");
    $(".pnlFail").slideUp("slow");
    $(".pnlAlert").slideUp("slow");
}

function Exhibit(className) {
    $("#pnlMessage").slideDown("slow");
    setTimeout(function () { $("#pnlMessage" + "." + className).slideUp("slow"); }, 10000);
}

function ShowAlertMessage(message) {
    var htmlMessageContent = ShowMessage("alert", message);
    $("body").append(htmlMessageContent);

    Exhibit("pnlAlert");
}

function ShowSuccessMessage(message) {
    var htmlMessageContent = ShowMessage("success", message);
    $("body").append(htmlMessageContent);
    $(".pnlSuccess #spnMessage").html(message);
    Exhibit("pnlSuccess");
}

function ShowFailMessage(message) {
    var htmlMessageContent = ShowMessage("fail", message);
    $("body").append(htmlMessageContent);
    $(".pnlFail #spnMessage").html(message);
    Exhibit("pnlFail");
}

function InformationBox(title, description, url, divPopup) {
    document.getElementById('spnTitleInformation').innerHTML = title;
    document.getElementById('spnTextInformation').innerHTML = description;
    var lnkClose = document.getElementById('lnkCloseInformation');
    if (url != null && url != "")
        lnkClose.href = url;
    else
        lnkClose.href = "javascript:CloseBox('" + divPopup + "')";
    LoadBox(divPopup);
}

function ConfirmBox(title, description, url, divPopup, confirmButton) {
    document.getElementById('spnTitleInformationConfirm').innerHTML = title;
    document.getElementById('spnTextInformationConfirm').innerHTML = description;
    document.getElementById('lnkConfirm').href = confirmButton;

    LoadBox(divPopup);
}

function DisplayElement(divCurrentDisplay) {
    if (document.getElementById(divCurrentDisplay).className == 'divComunityReportBoxClosed') {
        document.getElementById(divCurrentDisplay).className = 'divComunityReportBoxOpen';
    }
    else {
        document.getElementById(divCurrentDisplay).className = 'divComunityReportBoxClosed';
    }
}

function DisplayTextBox(obj, DivIdText) {
    var id = obj.id.split('_')[obj.id.split('_').length - 1];
    id = obj.id.replace(id, DivIdText);

    var idcheckBox = null;

    if (document.all) {
        idcheckBox = obj.lastChild.childNodes[obj.lastChild.children.length - 1].lastChild.children[0].id;
    }
    else {
        idcheckBox = obj.childNodes[1].rows[obj.childNodes[1].rows.length - 1].childNodes[1].childNodes[0].id;
    }

    if (document.getElementById(idcheckBox).checked) {
        if (document.getElementById(id).style.display == 'none') {
            document.getElementById(id).style.display = 'block';
        }
        else {
            document.getElementById(id).style.display = 'none';
        }
    }
    else {
        if (document.getElementById(id).style.display == 'block') {
            document.getElementById(id).style.display = 'none';
        }
    }
}

function ShowAccordion(divToOpenContent, divToOpenHead) {
    var groupdiv = document.getElementById("divAccordion").getElementsByTagName("div");

    for (var i = 0; i < groupdiv.length; i++) {
        var divID = groupdiv[i].id.split('_')[0];
        if (divID == "IDHeader" && groupdiv[i].id != divToOpenHead) {
            groupdiv[i].className = 'divHeaderClosed';
            continue;
        }
        if (divID == "IDContent" && groupdiv[i].id != divToOpenContent) {
            groupdiv[i].style.display = 'none';
            continue;
        }
    }

    if (document.getElementById(divToOpenHead).className != 'divHeaderOpened') {
        document.getElementById(divToOpenHead).className = 'divHeaderOpened';
        document.getElementById(divToOpenContent).style.display = 'block';
    }
    else {
        document.getElementById(divToOpenHead).className = 'divHeaderClosed';
        document.getElementById(divToOpenContent).style.display = 'none';
    }
}

function ShowAccordionCallCenter(divToOpenContent, divToOpenHead, walletId, msisdn, ownerid, idcommunity) {
    var groupdiv = document.getElementById("divAccordion").getElementsByTagName("div");
    for (var i = 0; i < groupdiv.length; i++) {
        var divID = groupdiv[i].id.split('_')[0];
        if (divID == "IDHeader" && groupdiv[i].id != divToOpenHead) {
            groupdiv[i].className = 'divHeaderClosed';

            continue;
        }
        if (divID == "IDContent" && groupdiv[i].id != divToOpenContent) {
            groupdiv[i].style.display = 'none';
            continue;
        }
    }

    if (document.getElementById(divToOpenHead).className != 'divHeaderOpened') {
        document.getElementById(divToOpenHead).className = 'divHeaderOpened';
        document.getElementById(divToOpenContent).style.display = 'block';
        $('#' + divToOpenHead).parent().find('.dark').removeClass('dark');
        $('#' + divToOpenHead).find('tr').addClass('dark');

        //$("#" + divToOpenContent).html("Carregando...");
        $("#" + divToOpenContent).html("<div id=\"tabs\"><ul><li><a href=\"#forms\" onclick=\"changeTab(this);\">Dados do Usu&aacute;rio</a></li><li><a href=\"#flows\" onclick=\"changeTab(this);\">Navega&ccedil;&otilde;es dispon&iacute;veis</a></li></ul></div>");
        var tabs = $("#" + divToOpenContent).children("#tabs");
        var divForms = $('<div id=\"forms\"><div class="formInfoMessage">Carregando Dados...</div></div>');
        var divFlows = $('<div id=\"flows\"><div class=\"flowinfoMessage\">Carregando Navega&ccedil;&otilde;es...</div></div>');
        tabs.append(divForms);
        tabs.append(divFlows);
        tabs.tabs();
        tabs.children('ul').removeClass('ui-corner-all');
        tabs.removeClass('ui-corner-all');
        tabs.children('ul').addClass('ui-tabs');
        FormView(walletId, msisdn, divToOpenContent, divForms, divToOpenHead, ownerid, idcommunity);
        GetFlows(walletId, msisdn, divToOpenContent, divFlows, divToOpenHead, ownerid, idcommunity);
    }
    else {
        document.getElementById(divToOpenHead).className = 'divHeaderClosed';
        document.getElementById(divToOpenContent).style.display = 'none';
        $('#' + divToOpenHead).find('tr').removeClass('dark');
    }
}

function changeTab(element) {
  $(element).parent().parent().parent().children('div').hide();
  $(element).parent().parent().parent().children($(element).attr('href')).show();  
}

function MpaView(flowId, walletid, ownerid) {
    //Máscara para cobrir a tela
    $('body').append('<div id="mask"></div>');
    $('#ifrmMPA').attr('src', $('#MPAView').val() + '/' + ownerid + '?walletid=' + walletid + '&idflow=' + flowId + '&isreadonly=true');
    Modal('#ViewFlow');
}

function FeedbackView(urlFeedback,projectName) {
    //Máscara para cobrir a tela
    $('body').append('<div id="mask"></div>');
    $('#ifrmFeedback').attr('src', urlFeedback + '/' + projectName );
    Modal('#ViewFeedback');
  }

function FormView(walletid, Msisdn, divToOpenContent, elementcontent, divToOpenHead, ownerid, idcommunity) {
  $.ajax({ url: '/web/_AjaxRequest.aspx?address=' + $('#MpaUrlApi').val() + 'forms/' + walletid + '/defaultflow/forms',
    cache: false,
    type: 'GET',
    success: function (json) {
      if (!json || !json[0]) {
        elementcontent.html('<div class="formInfoMessage">A Navega&ccedil;&atilde;o padr&atilde;o da comunidade n&atilde;o possui formul&aacute;rio.</div>');
        return;
      }
      elementcontent.html('');
      if (json[1]) {
        var comboBox = $('<select id="cbxform" class="formComboBox" onchange="GetForm(\'' + walletid + '\', \'' + Msisdn + '\', \'' + divToOpenContent + '\', $(\'#' + divToOpenContent + '\').find(\'#' + elementcontent.attr('id') + '\'), \'' + divToOpenHead + '\',  \'' + ownerid + '\', \'' + idcommunity + '\', $(this).val() )" ></select>');
        elementcontent.html('<div class="formInfoMessage">Escolha um Formul&aacute;rio para ver os dados respondidos.</div>');
        $.each(json, function (index, item) {
          comboBox.append('<option value="' + item.Id + '">' + item.Title + '</option>');
        });
        elementcontent.append(comboBox);
      }

      GetForm(walletid, Msisdn, divToOpenContent, elementcontent, divToOpenHead, ownerid, idcommunity, json[0].Id);
    },
    dataType: 'json',
    error: function () {
      elementcontent.html("<div class=\"formInfoMessage\">" + messageErrorAcessServer + "</div>");
    }
  });
}

function GetForm(walletid, Msisdn, divToOpenContent, elementcontent, divToOpenHead, ownerid, idcommunity, idForm) {
  if (idForm == "") {
    elementcontent.find('.tableReport').remove();
    return;
  }

  $.ajax({ url: '/web/_AjaxRequest.aspx?address=' + $('#MpaUrlApi').val() + 'forms/' + walletid + '/defaultflow/' + idForm + '/' + Msisdn,
    cache: false,
    type: 'GET',
    success: function (json) {
      elementcontent.find('.tableReport').remove();
      var idDivToOpenContent = '#' + divToOpenContent;
      if (json || json != null) {
        var elementForm = $("<table class=\"tableReport\"></table>");

        elementForm.append("<tr><th>Pergunta</th><th>Resposta</th><th>Data</th></tr>");
        var line = 1
        for (var i = 0; i < json.length; i++) {
          line = line * -1
          elementForm.append(CreateLine(json[i], line));
        }
      }
      elementcontent.append(elementForm);
    },
    dataType: 'json',
    error: function () {
      elementcontent.html("<div class=\"formInfoMessage\">" + messageErrorAcessServer + ".</div>");
    }
  }); 
}

function GetFlows(walletId, msisdn, divToOpenContent, elementcontent, divToOpenHead, ownerid, idcommunity) {
  var urlAjax = $('#MpaUrlApi').val() + 'flows/' + walletId + '/' + msisdn;
  $.ajax({ url: '/web/_AjaxRequest.aspx?address=' + urlAjax,
    dataType: 'json',
    cache: false,
    type: 'GET',
    success: function (json) {
      var idDivToOpenContent = '#' + divToOpenContent;
      elementcontent.html("");
      var element = $("<div class=\"flowContent\"></div>");
      element.append("<div class=\"flowinfoMessage\">Selecione uma navega&ccedil;&atilde;o para defin&iacute;-la como ativa.</div>");
      var dateTime = new Date();

      for (var i = 0; i < json.Flows.length; i++) {
        var isActive;
        var interface = "";
        var created = "";

        if (json.Flows[i].ActiveFlow) {
          var dateTime = eval('new ' + json.Flows[i].ActiveFlow.Created.slice(1, -1));
          isActive = "checked";
          interface = json.Flows[i].ActiveFlow.InterfaceName;
          created = ConvertDateToString(dateTime);
        } else {
          isActive = "";
        }

        element.append(CreateFlowItem(divToOpenContent, divToOpenHead, walletId, msisdn, ownerid, idcommunity, json.Flows[i], isActive, interface, created));
      }

      elementcontent.append(element);
    },
    error: function () {
      elementcontent.html("<div class=\"flowinfoMessage\">" + messageErrorAcessServer + "</div>");
    }
  });
}

function CreateFlowItem(divToOpenContent, divToOpenHead, walletId, msisdn, ownerid, idcommunity, flow, isActive, interface, created) {
  var container = $("<div class=\"flowItem\"></div>");  
  var flowName = $("<div class=\"flowName\"><input title=\"Ativar\" type='radio' name='flowid' class='radioSetFlow' onClick='javascript:SetFlow(\"" + flow.FlowId + "\",\"" + msisdn + "\", \"" + walletId + "\", \"" + divToOpenHead + "\",\"" + divToOpenContent + "\", 3, \"" + ownerid + "\", \"" + idcommunity + "\")' " + isActive + " >" + flow.Name + "</input></div>")
  container.append(flowName);
  var flowIcons = $("<div class=\"flowIcons\"></div>");
  var flowView = $("<div class=\"flowView\"><a href=\"javascript:void(null)\" class=\"history\" onclick=\"MpaView('" + flow.FlowId + "','" + walletId + "', '" + ownerid + "')\" title=\"ver Navega&ccedil;&atilde;o\">ver Navega&ccedil;&atilde;o</a></div>")
  flowIcons.append(flowView);
  container.append(flowIcons);
  if (interface, created) {
    var flowDetails = $("<div class=\"flowDetails\"><a href=\"javascript:void(null);\" onclick=\"Details(this)\" title=\"Detalhes\">Detalhes</a></div>")
    flowIcons.append(flowDetails);
    var containerdetails = $("<div class=\"flowContainerDetails\"><div><b>Interface: </b>" + interface + "</div><div><b>Data: </b>" + created + "</div></div>");
    container.append(containerdetails);
  }
  return container;
}

function Details(element) {
  if ($(element).parent().parent().parent().children('.flowContainerDetails').is(":hidden")){
    $(element).parent().parent().parent().children('.flowContainerDetails').show();
    return;
  }
  if ($(element).parent().parent().parent().children('.flowContainerDetails').is(":visible")) {
    $(element).parent().parent().parent().children('.flowContainerDetails').hide();
    return;
  }
  
}

function CreateLine(object, line) {
  var sdateTime = '-';  

  if (object.DateAnswer != null) {
    var dateTime = eval('new ' + object.DateAnswer.slice(1, -1));
    var sdateTime = ConvertDateToString(dateTime);
  }

  return $('<tr class="' + (line > 0 ? 'dark' : '') + '"><td>' + object.Question + '</td><td>' + object.Answer + '</td><td>' + sdateTime + '</td></tr>');
}

function ConvertDateToString(dateTime) {
  var auxDate = new Date(Date.UTC(dateTime.getFullYear(), dateTime.getMonth(), dateTime.getDate(), dateTime.getHours(), dateTime.getMinutes(), dateTime.getSeconds()));
  return auxDate.localeFormat('dd/MM/yyyy - HH:mm:ss');
}

function SetFlow(flowId, msisdn, wid, divToOpenHead, divToOpenContent, interface, ownerid, idcommunity) {
  var urlAjax = $('#MpaUrlApi').val() + 'flows/' + wid + '/' + flowId + '/' + msisdn + '/' + interface;

  $.ajax({ url: '/web/_AjaxRequest.aspx?address=' + urlAjax,
    dataType: 'json',
    cache: false,
    type: 'GET',
    success: function (data) {
      if (data) {
        ShowSuccessMessage("Fluxo alterado");
        $("#" + wid).addClass("ActiveStatus");

        var idOperation;
        if ($("#" + wid).html() == "Ativo")
          idOperation = 12;
        else
          idOperation = 11;

        $("#" + wid).html(CreateDivActiveInformation(data));
        ShowAccordionCallCenter(divToOpenContent, divToOpenHead, wid, msisdn, ownerid);
      }
      else
        ShowFailMessage("Erro ao alterar fluxo");

      ShowAccordionCallCenter(divToOpenContent, divToOpenHead, wid, msisdn, ownerid);
    }
  });
}

function GetActiveWallets(objJson) {
  $.post('/web/_AjaxRequest.aspx?address=' + $('#MpaUrlApi').val() + 'flows', JSON.stringify(objJson), function (json) {
    for (var i = 0; i < json.Wallets.length; i++) {
      var htmlStatus = "";
      if (json.Wallets[i].ActiveFlow) {
        $("#" + json.Wallets[i].WalletId).addClass("ActiveStatus");
        htmlStatus = CreateDivActiveInformation(json.Wallets[i].ActiveFlow);
      }
      else {
        htmlStatus = "<b>Inativo</b>";
        $("#" + json.Wallets[i].WalletId).removeClass("ActiveStatus");
      }
      $("#" + json.Wallets[i].WalletId).html(htmlStatus);
    }
  }, 'json');
}

function CreateDivActiveInformation(activeFlow) {
  return "<div><b>Ativo desde: </b>" + ConvertDateToString(eval('new ' + activeFlow.Created.slice(1, -1))) + "</div>" + "<div><b>Interface: </b>" + activeFlow.InterfaceName + "</div>";
}

function AlternateDiv(activeLink, objAba) {
    var groupDiv = document.getElementById("divAdvantage").getElementsByTagName("div");
    for (var i = 0; i < groupDiv.length; i++) {
        if (groupDiv[i].id != "" && document.getElementById(groupDiv[i].id).className == "tabbertab")
            document.getElementById(groupDiv[i].id).style.display = "none";
    }
    document.getElementById(objAba).style.display = "block";
    var groupLink = document.getElementsByName("aMenuLinkAbas");
    for (var i = 0; i < groupLink.length; i++) {
        document.getElementById(groupLink[i].id).className = "advantageInactive";
    }
    document.getElementById(activeLink).className = "advantageActive";
}

function descriptionReject(obj) {
    if (document.getElementById(obj).style.display == 'none') {
        document.getElementById(obj).style.display = 'block';
    }
    else {
        document.getElementById(obj).style.display = 'none';
    }
}

function EnterPress(btn, event) {
    var btnl = document.getElementById(btn);
    if (document.all) {
        if (event.keyCode == 13) {
            event.returnValue = false;
            event.cancel = true;
            btnl.click();
        }
    }
    else {
        if (event.which == 13) {
            clickSimulate(btn, 'click')
        }
    }
}

function clickSimulate(element, eventName) {
    if (document.all) {
        document.getElementById(element).focus();
        document.getElementById(element).click();
    }
    else {
        document.getElementById(element).focus();
        var oEvent = document.createEvent("MouseEvents");
        oEvent.initMouseEvent(eventName, true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, document.getElementById(element));
        document.getElementById(element).dispatchEvent(oEvent);
        document.getElementById(element).click();
    }
}

function ConfirmAddChannel(LinkButton) {
    __doPostBack(LinkButton, '');
    CloseBox('divInformationPopUpConfirm');
}

function alterFocus(current, maxlength, next) {
    if (current.value.length == maxlength) {
        document.getElementById(next).focus();
    }
}

function CheckBoxSelected(GroupNameCheckBox) {
    var idList = "";
    var checkBoxList = document.getElementsByName(GroupNameCheckBox);

    for (var i = 0; i < checkBoxList.length; i++) {
        if (checkBoxList[i].type == "checkbox") {
            if (checkBoxList[i].checked) {
                idList += checkBoxList[i].value + ';';
                idList += checkBoxList[i].nextSibling.nodeValue + '/';
            }
        }
    }

    return idList;
}

function CheckBoxUnSelected(GroupNameCheckBox) {
    var idList = "";
    var checkBoxList = document.getElementsByName(GroupNameCheckBox);

    for (var i = 0; i < checkBoxList.length; i++) {
        if (checkBoxList[i].type == "checkbox") {
            if (!checkBoxList[i].checked) {
                idList += checkBoxList[i].value + ';';
                idList += checkBoxList[i].nextSibling.nodeValue + '/';
            }
        }
    }

    return idList;
}

function ChannelSelected(GroupNameCheckBox) {

    var idChannels = CheckBoxSelected(GroupNameCheckBox);
    if (idChannels != null && idChannels != "") {
        uscCommunityListProviders.GetChannelSelected(idChannels);
    }
}

function CategorySelected(GroupNameCheckBox) {
    var idItem = CheckBoxSelected(GroupNameCheckBox);
    var unSelectedItem = CheckBoxUnSelected(GroupNameCheckBox);
    uscCommunityItemByCategory.CategoryUnSeleted(unSelectedItem);
    if (idItem != null && idItem != "") {
        uscCommunityItemByCategory.CategorySeleted(idItem);
    }
}

function ItemSelected(GroupNameCheckBox) {
    var idItem = CheckBoxSelected(GroupNameCheckBox);
    if (idItem != null && idItem != "") {
        uscCommunityListItemType.GetItemSelected(idItem);
    }
}

function ClearSelectedChannelSession() {
    uscCommunityListProviders.ClearSessionSelectedChannel();
    CloseBox('divInformationPopUpConfirm');
}

function ClearSessionCategory() {
    uscCommunityItemByCategory.ClearCategory();
}

function CloseMessage(divId) {
    var isVisible = $("#" + divId).is(":visible");
    if (isVisible)
        $("#" + divId).slideUp();
}

function DivVisibility(divId) {
    var isVisible = $("#" + divId).is(":visible");

    if (!isVisible)
        $("#" + divId).slideDown();
    else
        $("#" + divId).slideUp();
}

function SendToMailDivVisibility(obj, divId) {
    obj.className = obj.className == "aSendReports_closed" ? "aSendReports_opened" : "aSendReports_closed";
    DivVisibility(divId);
    DivVisibility("popupTable");
}

function WindowVisibility(obj, divId) {
    var idCurrentRadio = obj.defaultValue;

    if (idCurrentRadio == "rdbTypeInstant") {
        document.getElementById(divId).style.display = "none";
    }
    else {
        document.getElementById(divId).style.display = "block";
    }
}

function alternateVisibility(divRoot) {
    var groupDiv = document.getElementById(divRoot).getElementsByTagName("div");
    for (var i = 0; i < groupDiv.length; i++) {
        if (groupDiv[i].className == 'alternate') {
            groupDiv[i].style.display = groupDiv[i].style.display == 'block' ? 'none' : 'block';
        }
    }
}

function Counter(field, maxSize, idCount) {
    if ((field.value.length > maxSize)) {
        field.value = field.value.substring(0, maxSize);
    }
    document.getElementById(idCount).innerHTML = maxSize - field.value.length;
}

function ClientValidateAtLeastOneLetter(source, arguments) {
    arguments.IsValid = validator_AtLeastOneLetter(arguments.Value);
}

function ClientValidateCPF(source, arguments) {
    arguments.IsValid = validator_cpf(arguments.Value);
}

function ClientValidateCNPJ(source, arguments) {
    arguments.IsValid = validator_cnpj(arguments.Value);
}

function validator_cpf(cpf) {
    cpf = cpf.replace(/(\.|\(|\)|\/|\-| )+/g, '');
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    digitos_iguais = 1;
    if (cpf.length < 11)
        return false;
    for (i = 0; i < cpf.length - 1; i++)
        if (cpf.charAt(i) != cpf.charAt(i + 1)) {
            digitos_iguais = 0;
            break;
        }
    if (!digitos_iguais) {
        numeros = cpf.substring(0, 9);
        digitos = cpf.substring(9);
        soma = 0;
        for (i = 10; i > 1; i--)
            soma += numeros.charAt(10 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
            return false;
        numeros = cpf.substring(0, 10);
        soma = 0;
        for (i = 11; i > 1; i--)
            soma += numeros.charAt(11 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
            return false;
        return true;
    }
    else
        return false;
}

function validator_cnpj(cnpj) {
    if (cnpj.length == 0)
        return true;

    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    cnpj = cnpj.replace(/(\.|\(|\)|\/|\-| )+/g, '');
    digitos_iguais = 1;
    if (cnpj.length < 14 && cnpj.length < 15)
        return false;
    for (i = 0; i < cnpj.length - 1; i++)
        if (cnpj.charAt(i) != cnpj.charAt(i + 1)) {
            digitos_iguais = 0;
            break;
        }
    if (!digitos_iguais) {
        tamanho = cnpj.length - 2
        numeros = cnpj.substring(0, tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--) {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
            return false;
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0, tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--) {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
            return false;
        return true;
    }
    else
        return false;
}

function ShowTooltipCarrier(e, objctId) {
    var hint = document.getElementById(objctId);
    var posx = 0;
    var posy = 0;

    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft
  + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
  + document.documentElement.scrollTop;
    }

    //hint.innerHTML = req.responseText;;
    hint.style.top = posy + 10 + "px";
    hint.style.left = posx - 300 + "px";
    hint.style.display = 'block';
}

function HideTooltipCarrier(objctId) {
    document.getElementById(objctId).style.display = 'none';
}

function txtnumber(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (!evt) {
        evt = window.event;
    }
    var shiftkey = evt.shiftKey;
    if (!shiftkey) {
        if (charCode >= 96 && charCode <= 105 || charCode >= 48 && charCode <= 57 || charCode == 46 || charCode == 8 || charCode == 9) {
            return true;
        }
        else {
            return false;
        }
    }
    return false;
}

function gotTime(result) {
    window.parent.gotTime(result); // pass result up to the parent
}

function HideLabel(obj) {
    obj.style.backgroundImage = "none";
}
function ShowLabel(obj, url) {
    if (obj.value.length == 0)
        obj.style.backgroundImage = "url(style/imgs/" + url + ")";
    else
        obj.style.backgroundImage = "none";
}

function ShowAllLabels(obj, idPassword, imageUser, imagePassword) {
    ShowLabel(obj, imageUser);
    var id = obj.id.split('_')[obj.id.split('_').length - 1];
    id = obj.id.replace(id, idPassword);
    ShowLabel(document.getElementById(id), imagePassword);
}

function HideAllLabels(obj, idPassword) {
    HideLabel(obj);
    var id = obj.id.split('_')[obj.id.split('_').length - 1];
    id = obj.id.replace(id, idPassword);
    HideLabel(document.getElementById(id));
}

function HideShowDivDefined(divToShow, divToHide) {
    $("div[id*='" + divToShow + "']").show();
    $("div[id*='" + divToHide + "']").hide();

}

function AlternateShowDiv(idDiv1, idDiv2) {
    var div1 = $("div[id*='" + idDiv1 + "']");
    var div2 = $("div[id*='" + idDiv2 + "']");

    if (div1.is(":visible")) {
        div1.hide();
        div2.show();
    }
    else {
        div1.show();
        div2.hide();
    }
}

function AlternateShowDivSlide(idDiv1, idDiv2) {
    var div1 = $("div[id*='" + idDiv1 + "']");
    var div2 = $("div[id*='" + idDiv2 + "']");

    if (div1.is(":visible")) {
        div1.slideUp();
        div2.slideDown();
    }
    else {
        div1.slideDown();
        div2.slideUp();
    }
}

function Upload(filePath) {
    var validExtensions = new Array();
    var ext = filePath.value.substring(filePath.value.lastIndexOf('.') + 1).toLowerCase();
    validExtensions[0] = 'jpg';
    validExtensions[1] = 'jpeg';
    validExtensions[2] = 'bmp';
    validExtensions[3] = 'png';
    validExtensions[4] = 'gif';

    for (var i = 0; i < validExtensions.length; i++) {
        if (ext == validExtensions[i]) {
            __doPostBack('FileUpload1', '');
            return true;
        }
    }
    document.getElementById("MessageErro").innerHTML = 'Selecione arquivos de extens&atilde;o(jpg,jpeg,png ou gif)';
    return false;

}

function EnterChangeFocus(event, obj, idPassword) {
    HideAllLabels(obj, idPassword);

    if (document.all) {
        if (event.keyCode == 13) {
            event.returnValue = false;
            event.cancel = true;
            document.getElementById("ctl00_ctl00_uscAuthenticationPlace1_ctl01_txtPassword").focus();
        }
    }
    else {
        if (event.which == 13) {
            document.getElementById("ctl00_ctl00_uscAuthenticationPlace1_ctl01_txtPassword").focus();
        }
    }
}

//-----------------COLOR PICKER-----------

//Title:      FCP Combo-Chromatic Color Picker
//URL:        http://www.free-color-picker.com
//Product No. FCP201a
//Version:    1.2
//Date:       10/01/2006
//NOTE:       Permission given to use this script in ANY kind of applications IF
//            script code remains UNCHANGED and the anchor tag "powered by FCP"
//            remains valid and visible to the user.
//
//  Call:     showColorGrid3("input_field_id","span_id")
//  Add:      <DIV ID="COLORPICKER301" CLASS="COLORPICKER301"></DIV> anywhere in body
//*******************************************************************************
function getScrollY() {
    var scrOfX = 0,
    scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return scrOfY;
}
function gett6op6() {
    csBrHt = 0;
    if (typeof (window.innerWidth) == 'number') {
        csBrHt = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        csBrHt = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        csBrHt = document.body.clientHeight;
    }
    ctop = ((csBrHt / 2) - 132) + getScrollY();
    return ctop;
}
function getLeft6() {
    var csBrWt = 0;
    if (typeof (window.innerWidth) == 'number') {
        csBrWt = window.innerWidth;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        csBrWt = document.documentElement.clientWidth;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        csBrWt = document.body.clientWidth;
    }
    cleft = (csBrWt / 2) - 125;
    return cleft;
}
var nocol1 = "&#78;&#79;&#32;&#67;&#79;&#76;&#79;&#82;",
clos1 = "&#67;&#76;&#79;&#83;&#69;",
tt6 = "&#70;&#82;&#69;&#69;&#45;&#67;&#79;&#76;&#79;&#82;&#45;&#80;&#73;&#67;&#75;&#69;&#82;&#46;&#67;&#79;&#77;",
hm6 = "&#104;&#116;&#116;&#112;&#58;&#47;&#47;&#119;&#119;&#119;&#46;";
hm6 += tt6;
tt6 = "&#80;&#79;&#87;&#69;&#82;&#69;&#68;&#32;&#98;&#121;&#32;&#70;&#67;&#80;";
function setCCbldID6(objID, val) {
    document.getElementById(objID).value = val;
}
function setCCbldSty6(objID, prop, val) {
    switch (prop) {
        case "bc":
            if (objID != 'none') {
                document.getElementById(objID).style.backgroundColor = val;
            }
            break;
        case "vs":
            document.getElementById(objID).style.visibility = val;
            break;
        case "ds":
            document.getElementById(objID).style.display = val;
            break;
        case "tp":
            document.getElementById(objID).style.top = val;
            break;
        case "lf":
            document.getElementById(objID).style.left = val;
            break;
    }
}

function putOBJxColor6(OBjElem, Samp, pigMent) {
    if (pigMent != 'x') {
        setCCbldID6(OBjElem, pigMent);
        setCCbldSty6(Samp, 'bc', pigMent);
    }
    setCCbldSty6('colorpicker301', 'vs', 'hidden');
    setCCbldSty6('colorpicker301', 'ds', 'none');
}
function showColorGrid3(OBjElem, Sam) {
    document.getElementById(OBjElem).focus();
    var objX = new Array('00', '33', '66', '99', 'CC', 'FF');
    var c = 0;
    var z = '"' + OBjElem + '","' + Sam + '",""';
    var xl = '"' + OBjElem + '","' + Sam + '","x"';
    var mid = '';
    mid += '<center><table bgcolor="#FFFFFF" border="0" cellpadding="0" cellspacing="0" style="border: 1px solid rgb(240, 240, 240); padding: 1px;"><tr>';
    mid += "</tr><tr><td colspan='18' align='center' style='margin:0;padding:2px;height:14px;' ><input class='o5582n66' onkeypress='return false' type='text' disable='true' size='10' id='o5582n66' value='#FFFFFF'><input class='o5582n66a' type='text' size='2' style='width:14px;' id='o5582n66a' onclick='return false;' value='' style='border:solid 1px #666;'><a class='o5582n66' href='javascript:onclick=putOBJxColor6(" + z + ")'></a>&nbsp;&nbsp;&nbsp;&nbsp;<a class='o5582n66' href='javascript:onclick=putOBJxColor6(" + xl + ")'><span class='a01p3' style='width:80px; float:right;' >Fechar</span></a></td></tr><tr>";
    var br = 1;
    for (o = 0; o < 6; o++) {
        mid += '</tr><tr>';
        for (y = 0; y < 6; y++) {
            if (y == 3) {
                mid += '</tr><tr>';
            }
            for (x = 0; x < 6; x++) {
                var grid = '';
                grid = objX[o] + objX[y] + objX[x];
                var b = "'" + OBjElem + "', '" + Sam + "','#" + grid + "'";
                mid += '<td class="o5582brd" style="background-color:#' + grid + '"><a class="o5582n66"  href="javascript:onclick=putOBJxColor6(' + b + ');" onmouseover=javascript:document.getElementById("o5582n66").value="#' + grid + '";javascript:document.getElementById("o5582n66a").style.backgroundColor="#' + grid + '";  title="#' + grid + '"><div style="width:12px;height:14px;"></div></a></td>';
                c++;
            }
        }
    }
    mid += '</tr></table>';
    var objX = new Array('0', '3', '6', '9', 'C', 'F');
    var c = 0;
    var z = '"' + OBjElem + '","' + Sam + '",""';
    var xl = '"' + OBjElem + '","' + Sam + '","x"';
    mid += '<table bgcolor="#FFFFFF" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px #F0F0F0;padding:1px;"><tr>';
    var br = 0;
    for (y = 0; y < 6; y++) {
        for (x = 0; x < 6; x++) {
            if (br == 18) {
                br = 0;
                mid += '</tr><tr>';
            }
            br++;
            var grid = '';
            grid = objX[y] + objX[x] + objX[y] + objX[x] + objX[y] + objX[x];
            var b = "'" + OBjElem + "', '" + Sam + "','#" + grid + "'";
            mid += '<td class="o5582brd" style="background-color:#' + grid + '"><a class="o5582n66"  href="javascript:onclick=putOBJxColor6(' + b + ');" onmouseover=javascript:document.getElementById("o5582n66").value="#' + grid + '";javascript:document.getElementById("o5582n66a").style.backgroundColor="#' + grid + '";  title="#' + grid + '"><div style="width:12px;height:14px;"></div></a></td>';
            c++;
        }
    }
    mid += "</tr><tr><td colspan='18' align='right' style='padding:2px;border:solid 1px #FFF;background:#FFF;'><a href='" + hm6 + "' style='color:#666;font-size:8px;font-family:arial;text-decoration:none;lett6er-spacing:1px;'>" + tt6 + "</a></td>";
    mid += '</tr></table></center>';
    setCCbldSty6('colorpicker301', 'tp', '');
    //document.getElementById('colorpicker301').style.top = gett6op6();
    //document.getElementById('colorpicker301').style.left = getLeft6();
    setCCbldSty6('colorpicker301', 'vs', 'visible');
    setCCbldSty6('colorpicker301', 'ds', 'block');
    document.getElementById('colorpicker301').innerHTML = mid;
}

function SetTransparence(txtPreview, txtBackText) {
    document.getElementById(txtPreview).style.backgroundColor = "#FFFFFF";
    document.getElementById(txtBackText).value = "none";
}

function WidgetConstruct(url, identification, widgetFormat) {
    var subframe = document.createElement('iframe');
    subframe.id = 'iFrame' + widgetFormat;
    subframe.scrolling = "no";
    subframe.setAttribute("frameBorder", "no");
    subframe.src = url;

    switch (widgetFormat) {
        case "Horizontal":
            subframe.style.width = '655px';
            subframe.style.height = '207px';
            break;
        case "Vertical":
            subframe.style.width = '203px';
            subframe.style.height = '445px';
            break;
        case "Center":
            subframe.style.width = '300px';
            subframe.style.height = '370px';
            break;
        default:
            break;
    }
    document.getElementById('Torp_' + identification).appendChild(subframe);
    //subframe.contentWindow.bridgeGotTime = gotTime;
}
/*--------------funções Widget-----------------------*/

function WidgetAddUserCommunity(widgetFormat, idCommunity, url, idTxtDDD, idTxtPhone, idDDlCarrier, idDivSuccess, idLblError, idDivContent) {
    var lblError = document.getElementById(idLblError);
    lblError.innerHTML = '';
    var msisdn = document.getElementById(idTxtDDD).value + document.getElementById(idTxtPhone).value;
    var objCarrier = document.getElementById(idDDlCarrier);
    var carrier = objCarrier.options[objCarrier.selectedIndex].value;

    if (msisdn == '' || msisdn.length < 10) {
        lblError.innerHTML = 'O n&uacute;mero do telefone deve possuir 10 d&iacute;gitos.';
    }
    else {
        if (carrier == '-1') {
            lblError.innerHTML = 'Selecione sua operadora.';
        }
        else {
            var urlAddUser = 'http://' + url + '/web/WidgetUsuario.aspx?msisdn=' + msisdn + '&carrier=' + carrier + '&idcommunity=' + idCommunity + '&wFormat=' + widgetFormat + '&ref=' + location.href;

            try { pageTracker._trackEvent('Usuarios', 'click', 'Widget_Solicitaco_Usuario'); } catch (err) { }
            LoadURLHttpRequest(urlAddUser, 'divTorpedaoProccess');
            //AddIframe(idDivSuccess,urlAddUser,widgetFormat);
            AlternateShowDiv(idDivContent, idDivSuccess);
        }
    }
}

function WidgetResetFields(idTxtDDD, idTxtPhone, idDDlCarrier, idDivSuccess, idLblError, idDivContent) {
    document.getElementById(idLblError).innerHTML = '';
    document.getElementById(idTxtDDD).value = '';
    document.getElementById(idTxtPhone).value = '';
    var objCarrier = document.getElementById(idDDlCarrier);
    objCarrier.selectedIndex = 0;
    AlternateShowDiv(idDivContent, idDivSuccess);
}

function AddIframe(divToAddIframe, url, widgetFormat) {
    var subframe = document.createElement('iframe');
    document.getElementById(divToAddIframe).appendChild(subframe);
    subframe.id = 'iFrame' + widgetFormat;
    subframe.src = url;
    subframe.contentWindow.bridgeGotTime = gotTime;
}
/*--------------funções Widget-----------------------*/


function HideCountDown(divToHide) {
    try {
        CloseMessage(divToHide)
    }
    catch (Error)
    { }
}

/*Generic HttpRequest
Put the gif in path (style/images/ajax-loader.gif)
*/

function LoadURLHttpRequest(url, divName) {

    var xmlhttp = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
            xmlhttp = new XMLHttpRequest();
        }
        catch (e) {
            xmlhttp = false;
        }
        // branch for IE/Windows ActiveX version
    }
    else if (window.ActiveXObject) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                xmlhttp = false;
            }
        }
    }
    if (xmlhttp != null) {
        if (url.substr(url.lastIndexOf('.')).length > 5)
            url += '&';
        else
            url += '?';

        var now = new Date();
        url += 'd=' + now.getTime();

        xmlhttp.onreadystatechange = function () {
            document.getElementById(divName).innerHTML = "<img id='loadAjax' src='style/imgs/ajax-loader.gif' />";
            // if xmlhttp shows "loaded"
            // window.status = "StateChange: " + xmlhttp.readyState;
            if (xmlhttp.readyState == 4) {
                // if "OK"
                if (xmlhttp.status == 200) {
                    document.getElementById(divName).innerHTML = xmlhttp.responseText;
                    //alert(xmlhttp.responseText);
                }
                else {
                    //alert("Problem retrieving XML data")
                }
            }
        }
        xmlhttp.open("GET", url, true);

        xmlhttp.send("");
    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }

}

function ResourcesPreview(objectLink, tabToactivate) {
    $("[rel*='tab']").hide();
    $("[rel*='lnkPreview']").attr("class", 'optPageInactive');

    objectLink.className = 'optPageActive';
    $("[rel='" + tabToactivate + "']").show();
}

function RestrictQuantityMessageDay(quantityDay, obj) {
    var count = -1;

    $(".ListHoursSend input").each(function () {
        if ($(this).is(':checked')) {
            count++;
        }
    });

    if (count == quantityDay) {
        $('#' + obj.id).attr('checked', false);
        ShowAlertMessage("Voc&ecirc; pode realizar somente " + quantityDay + " envios di&aacute;rios.");
    }
}

//Request
function Request(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) {
        return "";
    } else {
        return results[1];
    }
}

function CopyField(fieldToGetValue, fieldToSetValue, nextFocus) {
    if (fieldToGetValue.val() == "")
        return;

    var beginDate = new Date(fieldToGetValue.val().split('/')[2], fieldToGetValue.val().split('/')[1], fieldToGetValue.val().split('/')[0]);
    var endDate = new Date(fieldToSetValue.val().split('/')[2], fieldToSetValue.val().split('/')[1], fieldToSetValue.val().split('/')[0]);

    if (beginDate > endDate)
        fieldToSetValue.val(fieldToGetValue.val());
}

function HideOpenDivAdvancedDetails(idDiv) {
    if ($("#" + idDiv).is(":visible")) {
        $('a.advancedDetails').css('background', 'url(../style/imgs/imgExpand.gif) no-repeat');
        $("#" + idDiv).hide();
    }
    else {
        $('a.advancedDetails').css('background', 'url(../style/imgs/imgColapse.gif) no-repeat');
        $("#" + idDiv).show();
    }
}

function HideOpenDiv(idDiv) {
    if ($("#" + idDiv).is(":visible")) {
        $("#" + idDiv).hide();
    }
    else {
        $("#" + idDiv).show();
    }
}

function HideOpenDivAndClearStatus(idDiv) {
    CloseMessageStatus();

    if ($("#" + idDiv).is(":visible")) {
        $("#" + idDiv).hide();
    }
    else {
        $("#" + idDiv).show();
    }
}

function HideOpenDivFade(idDiv) {
    if ($("#" + idDiv).is(":visible")) {
        $("#" + idDiv).fadeOut("slow");
    }
    else {
        $("#" + idDiv).fadeIn("slow");
    }
}

function HideOpenDivSlide(idDiv) {
    if ($("#" + idDiv).is(":visible")) {
        $("#" + idDiv).slideUp();
    }
    else {
        $("#" + idDiv).slideDown();
    }
}

function VisibilityTwitterContent() {
    if ($("input[id*='rbServices']:checked").val() == "3") {
        $("#divTwitterInfo").slideDown();
    }
    else {
        $("#divTwitterInfo").slideUp();
    }
}

function ShowHideDivByCheckBox(idCheckBox, idDiv) {
    if ($("input[id*='" + idCheckBox + "']").is(':checked')) {
        $("#" + idDiv).show();
    }
    else {
        $("#" + idDiv).hide();

    }
}

function RulesVisibilityElementsBusinessType() {
    var ddlBusinessType = $("#ctl00_ctl00_cphContent_cphContent_cWizardStep3_ddlBusinessType");
    var chkDegustation = $("#ctl00_ctl00_cphContent_cphContent_cWizardStep3_chkDegustation");
    var rdbNormal = $("#ctl00_ctl00_cphContent_cphContent_cWizardStep3_rblCommunityType_0");
    var rdbPremium = $("#ctl00_ctl00_cphContent_cphContent_cWizardStep3_rblCommunityType_1");
    var contentProvider = $("#ctl00_ctl00_cphContent_cphContent_cWizardStep3_pnlTypeContent");
    var divConfigTimeDegustation = $("#divConfigTimeDegustation");
    var divTypeCharge = $("#divTypeCharge");
    var isEdit = $("input[id*=txtNameCommunity]").val() != "";
    $("#divTwitterInfoContent").hide();
    $("#divServicesConfiguration").hide();

    chkDegustation.attr("disabled", true);
    //divTypeCharge.attr('disabled', false);

    divTypeCharge.show();
    contentProvider.show();

    if (chkDegustation.is(':checked'))
        divConfigTimeDegustation.show();
    else
        divConfigTimeDegustation.hide();

    switch (ddlBusinessType.val()) {
        case "1": //Grooling Tiger
            $("#divServicesConfiguration").show();
            chkDegustation.removeAttr("disabled");
            chkDegustation.parent().removeAttr("disabled");
            return;
            break;
        case "2": //Credit Package
            divTypeCharge.hide();
            $("#divServicesConfiguration").show();
            //divTypeCharge.attr('disabled', true);
            return;
            break;
        case "3": //Follower
            $("#divTwitterInfoContent").show();
            $("#divServicesConfiguration").show();
            chkDegustation.removeAttr("disabled");
            chkDegustation.parent().removeAttr("disabled");
            return;
            break;
        case "6": //Bundle
            divTypeCharge.hide();
            if (!isEdit)
                rdbPremium.attr('checked', 'checked');
            $("#divServicesConfiguration").show();
            return;
            break;
        case "5": //Interactivity
            if (!isEdit) {
                rdbNormal.removeAttr("checked");
                rdbPremium.attr('checked', 'checked');
            }
            contentProvider.hide();
            return;
            break;
        case "7": //Sponsored Follower
            divTypeCharge.hide();
            $("#divServicesConfiguration").show();
            return;
            break;
        case "8": //Navigation
            divTypeCharge.hide();
            contentProvider.hide();
            return;
            break;
        default:
            break;
    }
}

function CheckTrialDays(sender, args) {
    var days = $("input[id*='txtDaysDegustation']").val();

    if (days < 5 || days > 30) {
        args.IsValid = false;
        return;
    }

    args.IsValid = true;
    return;
}

function CalcAlertTrialDays() {
    var txtDaysDegustation = $("#ctl00_ctl00_cphContent_cphContent_cWizardStep3_txtDaysDegustation");
    var spnReimaningDays = $("#spnReimaningDays");
    //Tempo de alerta antes do término do período de degustação.
    var days = parseInt(txtDaysDegustation.val()) / 3;

    spnReimaningDays.text(Math.ceil(days));
}

function DisableEnableDiv(radioChecked, divId, disable) {
    if (disable) {
        $("div[id*='" + divId + "']").hide();

    }
    else {
        $("div[id*='" + divId + "']").show();
    }
}

function EmailValidate(value) {
    if (value == "")
        return true;
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return (filter.test(value));
}

function MultipleEmailValidate(value) {
    var result = true;
    if (value == "")
        result = true;

    var arr = value.split(/[,;]/);

    for (var i = 0; i < arr.length; i++) {
        var email = $.trim(arr[i]);
        if (!EmailValidate(email)) {
            return false;
        }
    }

    return result;
}

/*
VALIDATE FIELDS BY GROUP OF INPUTS

REQUIRED:       <input rel="rule:required:-1:8">
where:
required - represent the field is not empty.
-1       - Is the initial value of the field.(opitional) (The default value is "")
8        - Is the minimum quantity of char of the field. (opitional)

EMAIL VALIDATE:       <input rel="rule:email">
CPF VALIDATE:         <input rel="rule:cpf">
CNPJ VALIDATE:        <input rel="rule:cnpj">
MIN SIZE VALITADE:    <input rel="rule:size:10">
AT LEAST ONE LETTER:  <input rel="rule:atleastletter">
COMPARE 2 FIELDS:     <input rel="rule:compare:field1:field2">
CHECK VALID DATE:     <input rel="rule:date">

You can use more than one RULE in unique input.
Example:
<input rel="rule:required rule:email">
<input rel="rule:required:-1:8 rule:email">

In Asp.Net forms you should user this method in OnClientClick event.
The parameter contentId is an clustering of input to validate. (div, form, fieldset...)
Example:
<asp:Button ID="btnSend" runat="server" OnClientClick="return Validate('contentId')" />
*/
function CheckError(contentId) {
    var inputArray = $("div[id*='" + contentId + "'] :input");
    var cssClassAlert = "alertField";
    var errorCount = 0;

    inputArray.removeClass(cssClassAlert);
    inputArray.each(
    function (index, value) {
        if ($(this).attr('rel') != "") {
            var inputElement = $(value);

            if ($(value).attr('rel') != null && inputElement.is(":visible")) {
                var auxInputRules = $(value).attr('rel').split(" ");

                $.each(auxInputRules,
          function (index, value) {
              var arrayRule = value.split(":");
              var commandValue = arrayRule[1].toLowerCase() != null ? value.split(":")[1].toLowerCase() : "";

              var result = true;
              switch (commandValue) {
                  case "required":
                      inputElement.change(function () {
                          var resultChange = Required(arrayRule, inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = Required(arrayRule, inputElement.val());
                      break;
                  case "email":
                      inputElement.change(function () {
                          var resultChange = EmailValidate(inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = EmailValidate(inputElement.val());
                      break;
                  case "email_multiple":
                      inputElement.change(function () {
                          var resultChange = MultipleEmailValidate(inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = MultipleEmailValidate(inputElement.val());
                      break;
                  case "cpf":
                      inputElement.change(function () {
                          var resultChange = validator_cpf(inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = (validator_cpf(inputElement.val()))
                      break;
                  case "cnpj":
                      inputElement.change(function () {
                          var resultChange = validator_cnpj(inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = (validator_cnpj(inputElement.val()))
                      break;
                  case "compare":
                      inputElement.change(function () {
                          var resultChange = CompareValidator(arrayRule);
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = CompareValidator(arrayRule);
                      break;
                  case "size":
                      inputElement.change(function () {
                          var resultChange = CheckSize(inputElement.val(), arrayRule[2]);
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = CheckSize(inputElement.val(), arrayRule[2]);
                      break;
                  case "date":
                      inputElement.change(function () {
                          var resultChange = DateValidate(inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = DateValidate(inputElement.val());
                      break;
                  case "atleastletter":
                      inputElement.change(function () {
                          var resultChange = validator_AtLeastOneLetter(inputElement.val());
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = validator_AtLeastOneLetter(inputElement.val());
                      break;
                  case "minvalue":
                      inputElement.change(function () {
                          var resultChange = CheckMinimunValue(inputElement.val(), arrayRule[2]);
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = CheckMinimunValue(inputElement.val(), arrayRule[2]);
                      break;
                  case "maxvalue":
                      inputElement.change(function () {
                          var resultChange = CheckMaximunValue(inputElement.val(), arrayRule[2]);
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = CheckMaximunValue(inputElement.val(), arrayRule[2]);
                      break;
                  case "keyword":
                      inputElement.change(function () {
                          var resultChange = CheckKeyword(inputElement.context.id);
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = CheckKeyword(inputElement.context.id);
                      break;
                  case "comparedate": //check if start date is more than end date.
                      var dt1 = inputElement.val();

                      var dt2 = $("[id*='" + arrayRule[2] + "']").val();

                      inputElement.change(function () {
                          var resultChange = CompareDate(dt1, dt2);
                          if (result)
                              inputElement.removeClass(cssClassAlert);
                          else
                              inputElement.addClass(cssClassAlert);
                      });

                      result = CompareDate(dt1, dt2);
                      break;
                  default:
                      break;
              }
              if (!result) {
                  errorCount++;
                  inputElement.addClass(cssClassAlert);
                  if (errorCount == 1)
                      inputElement.focus();
              }
          }
          );
            }
        }
    }
  );
    return errorCount;
}

function validator_AtLeastOneLetter(argument) {
    if (argument == '' || argument == undefined)
        return true;

    return isNaN(argument);
}

function CompareDate(dt1, dt2) {
    var beginDate = new Date(dt1.split('/')[2], dt1.split('/')[1], dt1.split('/')[0]);
    var endDate = new Date(dt2.split('/')[2], dt2.split('/')[1], dt2.split('/')[0]);

    return beginDate <= endDate;
}

function CheckMinimunValue(value, minValue) {
    if (value == '' || value == undefined)
        return true;
    return parseInt(value) > parseInt(minValue);
}

function CheckMaximunValue(value, maxValue) {
    if (value == '' || value == undefined)
        return true;
    return parseInt(value) <= parseInt(maxValue);
}

function DateValidate(value) {

    var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
    var vdt = new Date();
    var vdia = vdt.getDay();
    var vmes = vdt.getMonth();
    var vano = vdt.getYear();


    if ((value.match(expReg)) && (value != '')) {
        var dia = value.substring(0, 2);
        var mes = value.substring(3, 5);
        var ano = value.substring(6, 10);

        if ((mes == 04 && dia > 30) || (mes == 06 && dia > 30) || (mes == 09 && dia > 30) || (mes == 11 && dia > 30)) {
            return false;
        }
        else {
            if (ano % 4 != 0 && mes == 2 && dia > 28) {
                return false;
            }
            else {
                if (ano % 4 == 0 && mes == 2 && dia > 29) {
                    return false;
                }
                else {
                    return true;
                }
            }
        }
    }
    else {
        return false;
    }
}

function CheckSize(val, size) {
    var length = val.length

    if (length == 0) {
        return true;
    }
    else {
        return (val.length == size);
    }
}

function ValidateWithMessage(divToValidate) {
    var errorCount = CheckError(divToValidate);

    if (errorCount > 0) {
        ShowAlertMessage("Voc&ecirc; deve preencher corretamente todos os campos.");
        return false;
    }
    return true;
}

function Validate(divToValidate, errorLabelId) {
    $("#" + errorLabelId).html("");
    var errorCount = CheckError(divToValidate);
    if (errorCount > 0) {
        $("#" + errorLabelId).html("Voc&ecirc; deve preencher corretamente todos os campos");
        return false;
    }
    return true;
}

function CompareValidator(arrayRule) {
    var input1 = $("input[id*='" + arrayRule[2] + "']").val();
    var input2 = $("input[id*='" + arrayRule[3] + "']").val();

    return (input1 == input2);
}

function Required(arrayRule, inputVal) {
    var commandDefaultValue = "";
    var commandMinSize = 0;

    if (arrayRule.length > 3)//verifica a quantidade de rules para o tipo required
    {
        commandDefaultValue = "";
        commandMinSize = arrayRule[3];
    }
    else
        if (arrayRule.length > 2)
            commandDefaultValue = arrayRule[2].toLowerCase();

    if (commandMinSize > 0 && inputVal.length < commandMinSize) {
        return false;
    }
    else {
        return (inputVal != commandDefaultValue);
    }
}

function VisibilityLogin(divVisibility, divMessageNews) {

    if ($("#" + divVisibility).is(":visible")) {
        $("#aAcceptRestrict").removeClass("loginOpened");
    }
    else {
        $("#aAcceptRestrict").addClass("loginOpened");

    }
    HideOpenDiv(divVisibility);
    if ($.cookie("message") == null) {
        HideNewsMessage(divMessageNews);
    }
}

function HideNewsMessage(divId) {
    $.cookie("message", "true");
    HideOpenDivFade(divId);
}

function ShowNewsMessage(divId) {
    if ($.cookie("message") != "true") {
        HideOpenDivFade(divId);
    }
}

//PageLoad
$(document).ready(function () {

    $(function () {
        $("[date*='true']").datepicker({
            numberOfMonths: 1,
            showOn: 'button',
            buttonImage: '../style/imgs/calendar.gif',
            buttonImageOnly: true,
            dateFormat: 'dd/mm/yy',
            dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
            monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
            showAnim: 'slideDown'
        });
        $("[date*='true']").mask("99/99/9999");
    });

    GetSelectedChannel();

    ShowNewsMessage("divLoginAlert");

    $('input[type="text"]').each(function () {
        if ($(this).attr('title') == '')
            return;

        this.value = $(this).attr('title');
        $(this).addClass('text-label');

        $(this).focus(function () {
            if (this.value == $(this).attr('title')) {
                this.value = '';
                $(this).removeClass('text-label');
            }
        });
        $(this).blur(function () {
            if (this.value == '') {
                this.value = $(this).attr('title');
                $(this).addClass('text-label');
            }
        });
    });

    $('input[type="password"]').each(function () {
        if ($(this).attr('title') != "Senha")
            return;

        var passwordClass = 'password-label';


        $(this).addClass(passwordClass);
        $(this).focus(function () {
            if ($.inArray("password-label", $(this).attr("class").split(' ')) == 1) {
                $(this).removeClass(passwordClass);
                this.value = '';
            }
        });
        $(this).blur(function () {
            if (this.value == '') {
                $(this).addClass(passwordClass);
            }
        });

    });
});

function OnlyNumber(e) {
    var code = GetCode(e);
    if (code == 127 || code == 8 || code == 9 || (code >= 48 && code <= 57))
        return true;
    else
        return false;
}

function ValidChars(e, chars) {
    var code = GetCode(e);
    if (code == 127 || code == 8 || code == 9 || code == 46 || code == 20)
        return true;
    var charsArray = chars.split(',');
    return $.inArray(String.fromCharCode(code), charsArray) >= 0;

}

function GetCode(e) {
    if (e.keyCode)
        return e.keyCode;
    else
        if (e.which)
            return e.which; // Netscape 4.?
        else
            if (e.charCode)
                return e.charCode; // Mozilla
}

function SetField(fieldId, value) {
    $("input[id*='" + fieldId + "']").val(value);
    return true;
}

/* Sticky Tooltip script (v1.0)
* Created: Nov 25th, 2009. This notice must stay intact for usage 
* Author: Dynamic Drive at http://www.dynamicdrive.com/
* Visit http://www.dynamicdrive.com/ for full source code
*/

var stickytooltip = {
    tooltipoffsets: [20, 20], //additional x and y offset from mouse cursor for tooltips
    fadeinspeed: 200, //duration of fade effect in milliseconds
    rightclickstick: true, //sticky tooltip when user right clicks over the triggering element (apart from pressing "s" key) ?
    stickybordercolors: ["black", "darkred"], //border color of tooltip depending on sticky state
    stickynotice1: ["Press \"s\"", "or right click", "to sticky box"], //customize tooltip status message
    stickynotice2: "Click outside this box to hide it", //customize tooltip status message

    //***** NO NEED TO EDIT BEYOND HERE

    isdocked: false,

    positiontooltip: function ($, $tooltip, e) {
        var x = e.pageX + this.tooltipoffsets[0], y = e.pageY + this.tooltipoffsets[1]
        var tipw = $tooltip.outerWidth(), tiph = $tooltip.outerHeight(),
        x = (x + tipw > $(document).scrollLeft() + $(window).width()) ? x - tipw - (stickytooltip.tooltipoffsets[0] * 2) : x
        y = (y + tiph > $(document).scrollTop() + $(window).height()) ? $(document).scrollTop() + $(window).height() - tiph - 10 : y
        $tooltip.css({ left: x, top: y })
    },

    showbox: function ($, $tooltip, e) {
        $tooltip.fadeIn(this.fadeinspeed)
        this.positiontooltip($, $tooltip, e)
    },

    hidebox: function ($, $tooltip) {
        if (!this.isdocked) {
            $tooltip.stop(false, true).hide()
            $tooltip.css({ borderColor: 'black' }).find('.stickystatus:eq(0)').css({ background: this.stickybordercolors[0] }).html(this.stickynotice1)
        }
    },

    docktooltip: function ($, $tooltip, e) {
        this.isdocked = true
        $tooltip.css({ borderColor: 'darkred' }).find('.stickystatus:eq(0)').css({ background: this.stickybordercolors[1] }).html(this.stickynotice2)
    },


    init: function (targetselector, tipid) {
        jQuery(document).ready(function ($) {
            var $targets = $(targetselector)
            var $tooltip = $('#' + tipid).appendTo(document.body)
            if ($targets.length == 0)
                return
            var $alltips = $tooltip.find('div.atip')
            if (!stickytooltip.rightclickstick)
                stickytooltip.stickynotice1[1] = ''
            stickytooltip.stickynotice1 = stickytooltip.stickynotice1.join(' ')
            stickytooltip.hidebox($, $tooltip)
            $targets.bind('mouseenter', function (e) {
                $alltips.hide().filter('#' + $(this).attr('data-tooltip')).show()
                stickytooltip.showbox($, $tooltip, e)
            })
            $targets.bind('mouseleave', function (e) {
                stickytooltip.hidebox($, $tooltip)
            })
            $targets.bind('mousemove', function (e) {
                if (!stickytooltip.isdocked) {
                    stickytooltip.positiontooltip($, $tooltip, e)
                }
            })
            $tooltip.bind("mouseenter", function () {
                stickytooltip.hidebox($, $tooltip)
            })
            $tooltip.bind("click", function (e) {
                e.stopPropagation()
            })
            $(this).bind("click", function (e) {
                if (e.button == 0) {
                    stickytooltip.isdocked = false
                    stickytooltip.hidebox($, $tooltip)
                }
            })
            $(this).bind("contextmenu", function (e) {
                if (stickytooltip.rightclickstick && $(e.target).parents().andSelf().filter(targetselector).length == 1) { //if oncontextmenu over a target element
                    stickytooltip.docktooltip($, $tooltip, e)
                    return false
                }
            })
            $(this).bind('keypress', function (e) {
                var keyunicode = e.charCode || e.keyCode
                if (keyunicode == 115) { //if "s" key was pressed
                    stickytooltip.docktooltip($, $tooltip, e)
                }
            })
        }) //end dom ready
    }
}

//stickytooltip.init("targetElementSelector", "tooltipcontainer")
stickytooltip.init("*[data-tooltip]", "mystickytooltip")

function PersonalizeWidget(selectedType) {
    var divPreview = $("#divPreview");
    var lnkFlash = $("#lnkFlash");
    var lnkHTML = $("#lnkHtml");

    if (selectedType == "html" || selectedType == "flash") {
        $("[id*=hdnType]").val(selectedType);
    }
    lnkHTML.removeClass("selected");
    lnkFlash.removeClass("selected");

    var idCommunity = $("[id*=hdnIdCommunity]").val();
    var isPremium = $("[id*=hdnIsPremium]").val();
    var idBusinessType = $("[id*=hdnIdBusinessType]").val();
    var width = $("[id*=txtWidth]").val();
    var height = $("[id*=txtHeight]").val();
    var color = $("[id*=txtTextColor]").val();
    var font = $("[id*=ddlFont]").val();
    var absolutePath = $("[id*=hdnAbsolutePath]").val();
    var communityGuid = $("[id*=hdnCommunityGuid]").val();
    var idOwner = $("[id*=hdnOwner]").val();
    var prefix = $("[id*=hdnPrefix]").val();
    var ownerGuid = $("[id*=hdnOwnerGuid]").val();

    var ddlCommunity = $("[id*=ddlCommunityWidget]").val();

    if (ddlCommunity != "0" && ddlCommunity != undefined) {
        if ($("[id*=hdnIdCommunity]").val().indexOf(ddlCommunity) == -1) {
            $("[id*=hdnIdCommunity]").val(idCommunity + "|" + ddlCommunity);
            idCommunity = $("[id*=hdnIdCommunity]").val();
        }
    }

    idCommunity = $("[id*=hdnIdCommunity]").val();
    var txtCode = $("[id*=txtCode]");

    if ($("[id*=hdnType]").val() == 'html') {
        lnkHTML.addClass("selected");
        var src = 'http://app.torpedao.com.br/web/_widgetSimple.aspx?font=' + font + '&fontsize=11&width=' + width + '&idcm=' + idCommunity + '&ispremium=' + isPremium + '&idbt=' + idBusinessType + '&color=' + color + '&height=' + height + '&prefix=' + prefix + '&userGUID=' + ownerGuid;
        var iframe = '<iframe id="iFrameTopedao" frameBorder="no" ALLOWTRANSPARENCY="true" scrolling="no" src="' + src + '" width="' + width + 'px" height="' + height + 'px"></iframe>';
        txtCode.val(iframe);
        divPreview.html(iframe);
    }
    else {
        lnkFlash.addClass("selected");
        var url = 'http://app.torpedao.com.br/web/flash/widgetCustomP.swf?clrfont=' + color + '&idBT=' + idBusinessType + '&ispremium=' + isPremium.toLowerCase() + '&font=' + font + '&idow=' + idOwner + '&idcom=' + idCommunity + '&guid=' + communityGuid + '&prefix=' + prefix + '&widthW=' + width + '&heightW=' + height + '&userGUID= ' + ownerGuid + '&ordomain=http://' + absolutePath + '/';

        var objectSwf = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" id="TorpedaoWidget" width="' + width + '" height="' + height + '"> <param name="movie" value="';
        objectSwf += url;
        objectSwf += '" />			  <param name="quality" value="high" />			  <param name="wmode" value="transparent"> 			  <embed src="';
        objectSwf += url;
        objectSwf += '"         quality="high"         align="middle"        pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash"         type="application/x-shockwave-flash"         width="' + width + '" height="' + height + '"         name="TorpedaoWidget"        wmode="transparent">      </embed>		</object>'

        txtCode.val(objectSwf);
        divPreview.html(objectSwf);

    }
}

function HideDiv(div1, div2) {
    $("#" + div2).hide();
    $("#" + div1).hide();
}

function ShowHideDiv(idCheckBox, idDiv, idDivToHide) {
    if ($("input[id*='" + idCheckBox + "']").is(':checked')) {
        $("#" + idDiv).show();
        $("#" + idDivToHide).hide();
    }
    else {
        $("#" + idDiv).hide();
    }

}

function PublishInstantNewsConfirm(div1, div2) {
    if (!ValidateWithMessage('divInstantMessageContent'))
        return false;

    var text = $("textarea[id*='txtSms']").val();
    if (text.length > 125) {
        ShowAlertMessage("A mensagem deve ter no m&aacute;ximo 125 caracteres.");
        return false;
    }


    $("span[id*='spnNews']").html(text);

    AlternateShowDiv(div1, div2);
}

function PublishInstantNews(divId, element) {

    if (!$("#" + divId).is(":visible")) {
        $("#" + element).addClass("checked");
    }
    else {
        $("#" + element).removeClass("checked");
    }

    HideOpenDivSlide(divId);
}

/*Ajax Methods*/

function CallcenterMessageNewsResend(idPackage, msisdn, appSpecifc) {
    if (msisdn == "") {
        ShowAlertMessage("Informe o n&uacute;mero do celular para prosseguir.");
        return;
    }

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=newsresend&parameters=" + idPackage + ";" + msisdn + "|" + appSpecifc,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;
    if (resp == 'true') {
        ShowSuccessMessage("A mensagem foi reenviada com sucesso.");
    }
    else {
        ShowFailMessage("N&atilde;o foi poss&iacute;vel reenviar esta mensagem no momento.");
    }
    return;
}

function UserLogin(txtUserId, txtPasswordId, divToValidateFields, labelError) {
    $("#" + labelError).html("");
    if (!Validate(divToValidateFields, labelError))
        return false;

    var user = $("#" + txtUserId).val();
    var password = $("#" + txtPasswordId).val();

    var urlAjax = "_AjaxMethods.aspx";

    var resp = $.ajax({
        type: "POST",
        data: "parameters=" + user + "|" + password + "&function=userlogin",
        url: urlAjax,
        cache: false,
        async: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
        beforeSend:
                    function () { $("#divLoading").show(); }
    }).responseText;

    switch (resp.split(';')[0]) {
        case "0":
            if (Request("redir") != "") {
                window.location = resp.split(';')[1] + "/default.aspx?redir=" + Request("redir");
            }
            else {
                $(location).attr('href', resp.split(';')[1] + "/default.aspx");
            }
            break;
        case "-1":
            $("#" + labelError).html("Usu&aacute;rio ou senha inv&aacute;lidos.");
            $("#divLoading").hide();
            return false;
            break;
        default:
            $("#" + labelError).html("Servi&ccedil;o indispon&iacute;vel no momento.");
            $("#divLoading").hide();
            return false;
            break;
    }
}

function NewsGetSMSContent(idIndex) {
    HideOpenDiv('divNews_' + idIndex);

    if ($("[id*='" + idIndex + "_txtResponse']").val() == "") {
        var idNewsContent = $("[id*='" + idIndex + "_hdnFeedData']").val();

        $.ajax({
            url: "../_AjaxMethods.aspx?function=newsgetsmscontent&parameters=" + idNewsContent,
            cache: false,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            async: true,
            beforeSend: function (resp) {
                $("[id*='" + idIndex + "_txtResponse']").attr("disabled", "disabled");
                $("[id*='" + idIndex + "_txtResponse']").val("Carregando...");
            },
            success: function (resp) {
                $("[id*='" + idIndex + "_txtResponse']").attr("disabled", "");
                $("[id*='" + idIndex + "_txtResponse']").val(resp);
            }
        });
    }
    return false;
}

function CheckEmail(idTxtEmail) {
    var email = $("[id*='" + idTxtEmail + "']");
    email.removeClass("alertField");

    if (email.val() != '') {
        var resp = $.ajax({
            url: "../_AjaxMethods.aspx?function=checkemail&parameters=" + email.val(),
            cache: false,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            async: false
        }).responseText;
        if (resp != 'true') {
            ShowAlertMessage("O e-mail inserido j&aacute; existe em nossa base de dados. Aguarde a aprova&ccedil;&atilde;o do seu cadastro.");
            email.addClass("alertField");
        }
    }
    return;
}

function UserLogout() {

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=userlogout",
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;
    window.location = "../";
    return false;
}

function CheckMsisdn(idTxtPhoneDDD, idTxtPhoneCel) {
    var inputDDD = $("[id*='" + idTxtPhoneDDD + "']");
    var inputNumber = $("[id*='" + idTxtPhoneCel + "']");

    inputDDD.removeClass("alertField");
    inputNumber.removeClass("alertField");

    var msisdn = inputDDD.val() + inputNumber.val();
    if (msisdn != '') {
        var resp = $.ajax({
            url: "../_AjaxMethods.aspx?function=checkmsisdn&parameters=" + msisdn,
            cache: false,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            async: false
        }).responseText;
        if (resp != 'true') {
            ShowAlertMessage("O celular inserido j&aacute; existe em nossa base de dados.");
            inputDDD.addClass("alertField");
            inputNumber.addClass("alertField");
        }

    }
    return;
}

function CheckMsisdnFull(idTxtPhone) {
    var inputNumber = $("[id*='" + idTxtPhone + "']");
    inputNumber.removeClass("alertField");

    var msisdn = inputNumber.val().replace("(", "").replace(")", "").replace("-", "");
    if (msisdn != '') {
        var resp = $.ajax({
            url: "../_AjaxMethods.aspx?function=checkmsisdn&parameters=" + msisdn,
            cache: false,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            async: false
        }).responseText;
        if (resp != 'true') {
            ShowAlertMessage("O celular inserido j&aacute; existe em nossa base de dados.");            
            inputNumber.addClass("alertField");
        }

    }
    return;
}

function CheckKeyword(idkeyword) {
    var inputKeyword = $("[id*='" + idkeyword + "']");
    inputKeyword.removeClass("alertField");

    if (inputKeyword.val() != '') {
        var resp = $.ajax({
            url: "../_AjaxMethods.aspx?function=checkkeyword&parameters=" + inputKeyword.val(),
            cache: false,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            async: false
        }).responseText;
        if (resp != 'true') {
            ShowAlertMessage("A palavra-chave inserida n&atilde;o est&aacute; dispon&iacute;vel.");
            inputKeyword.addClass("alertField");
            return false;
        }
    }
    return true;
}

function GetJsonFeeds(idSection) {

    if (idSection != "-1") {
        $.ajax({
            url: "../_AjaxMethods.aspx?function=getjsonfeeds&parameters=" + idSection,
            cache: false,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            async: true,
            beforeSend: function (resp) {
                $("#divInstantMessageContent select[id*='ddlEdition']").attr("disabled", "disabled");
                $("#divInstantMessageContent select[id*='ddlEdition']").html("<option value='-1'>Carregando...</option>");
            },
            success: function (resp) {
                $("#divInstantMessageContent select[id*='ddlEdition']").attr("disabled", "");
                if (resp == "") {
                    ShowAlertMessage("Esta se&ccedil;&atilde;o n&atilde;o possui editorias cadastradas.");
                }
                else {
                    $("#divInstantMessageContent select[id*='ddlEdition']").html("<option value='-1'>Selecione...</option>");
                    $(resp).appendTo("#divInstantMessageContent select[id*='ddlEdition']");
                }
            }
        });
    }
    else {
        $("#divInstantMessageContent select[id*='ddlEdition']").html("<option value='-1'>Selecione...</option>");
    }
}

function SaveInstantNews() {
    var idFeed = $("#divInstantMessageContent select[id*='ddlEdition']").val();
    var message = $("#divInstantMessageContent textarea[id*='txtSms']").val();

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=saveinstantnews&parameters=" + idFeed + "|" + message,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;

    if (resp == "True") {
        $("#divInstantMessageContent select[id*='ddlSection'] option:first").attr('selected', 'selected');
        $("#divInstantMessageContent select[id*='ddlEdition']").html("<option value='-1'>Selecione...</option>");
        $("#divInstantMessageContent textarea[id*='txtSms']").val("");
        AlternateShowDiv("divInstantMessageConfirm", "divInstantMessageContent");
        PublishInstantNews("divInstantMessage", "btnPublishNews");
        ShowSuccessMessage("Not&iacute;cia publicada com sucesso.");
    }
    else {
        ShowFailMessage("Não foi poss&iacute;vel publicar a not&iacute;cia no momento. Tente novamente mais tarde.");
    }
}

function UserFilter(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 13) {
        return false;
    }
    $("ul.listUsers li").hide();

    var text;
    var count = 0;

    $("ul.listUsers li").each(function (index, item) {
        text = $(item).text().toUpperCase();
        if (text.indexOf($(":text#txtSearch").val().toUpperCase()) != -1) {
            $(item).show();
            count++;
        }
    });
    if (count == 0) {
        $("#notFound").show();
    }
    else {
        $("#notFound").hide();
    }
    return true;
}

function SaveRoleUser(element) {
    var idUserDetails = $("a.selected span.userName").attr("rel");
    var idRole = $(element).parent().attr("rel");
    var isActive = $(element).is(":checked");

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=saveroleuser&parameters=" + idRole + "|" + idUserDetails + "|" + isActive,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;

    $(element).parent().fadeOut("fast");
    $(element).parent().fadeIn("fast");
    $(element).parent().removeClass("fail");
    $(element).parent().removeClass("success");
    if (resp == "True") {
        $(element).parent().parent().removeClass("fail");
        $(element).parent().parent().addClass("success");
        ShowSuccessMessage("Permiss&atilde;o atribu&iacute;da com sucesso ao usu&aacute;rio " + $("a.selected span.userName").text() + ".");
    }
    else {
        $(element).parent().addClass("fail");
        ShowFailMessage("Erro ao atribuir a permiss&atilde;o " + $(element).val() + " ao usu&aacute;rio " + $("a.selected span.userName").text() + ".");
        $(element).attr("checked", !isActive);
    }
}

function DeleteUserAgent() {
    var idUserDetails = $("a.selected span.userName").attr("rel");

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=DeleteUserAgent&parameters=" + idUserDetails,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;

    if (resp == "true") {
        $("[rel=" + idUserDetails + "]").parent().parent().remove();
        ShowSuccessMessage("usu&aacute;rio " + $("a.selected span.userName").text() + " deletado com sucesso.");
    }
    else {
        ShowFailMessage("Erro ao deletar o usu&aacute;rio " + $("a.selected span.userName").text() + ".");
    }
}

function GetPermissions(idUserDetails, element) {
    $("ul.listUsers li a").removeClass("selected");
    $(element).addClass("selected");
    var idRole = $("a.selected span.userName").attr("rolemaster");
    $("#divPermission").hide("fast");

    var resp = $.ajax({
        url: "../_userPermission.aspx?iduserdetails=" + idUserDetails + "&idrolemaster=" + idRole,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: true,
        beforeSend: function (resp) {
            $(".loading").fadeIn("fast");
        },
        success: function (resp) {
            $(".loading").fadeOut("fast");
            var userName = $("[rel=" + idUserDetails + "]").text();
            $("#spnUser").text(userName);
            $("#divPermissions").html(resp);
            $("#divPermission").show("fast");
        }
    });
}

function GetProviders(e) {
    var type = $(e).attr("rel");
    $("#divTypeContent a").removeClass("selected");
    $(e).addClass("selected");
    $("#divCategory").slideUp();
    $("#divChannel").slideUp();
    $("#divProviderList").slideUp();

    var resp = $.ajax({
        url: "../subpages/_Providers.aspx?format=" + type,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: true,
        beforeSend: function (resp) {
            $(".loading").slideDown("fast");
        },
        success: function (resp) {
            $(".loading").slideUp("fast");
            $("#divProvider").html(resp);
            $("#divProvider").show("fast");
            $("#divProviderList").slideDown();
            Scroll(e);
        }
    });
}

function GetCategories(e) {
    var type = $("#divTypeContent a.selected").attr("rel");
    var idProvider = $(e).attr("rel");
    $("#divProviderList a").removeClass("selected");
    $(e).addClass("selected");
    $("#divChannel").slideUp();
    $("#txtSearchCategory").val("");
    $("#txtSearchChannel").val("");
    $("#divCategory #notFound").hide();


    var resp = $.ajax({
        url: "../subpages/_Category.aspx?format=" + type + "&idCategory=" + idProvider,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: true,
        beforeSend: function (resp) {
            $(".loading").slideDown("fast");
        },
        success: function (resp) {
            $(".loading").slideUp("fast");
            $("#divCategoryContent").html(resp);
            $("#divCategory").slideDown();
            $("#txtSearchCategory").focus();
            Scroll(e);
        }
    });
}

function GetChannels(e) {
    var type = $("#divTypeContent a.selected").attr("rel");
    var idCategory = $(e).attr("rel");
    $("#divCategoryContent a").removeClass("selected");
    $(e).addClass("selected");
    $("#divChannel #notFound").hide();

    var resp = $.ajax({
        url: "../subpages/_Channel.aspx?format=" + type + "&idCategory=" + idCategory,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: true,
        beforeSend: function (resp) {
            $(".loading").slideDown("fast");
        },
        success: function (resp) {
            $(".loading").slideUp("fast");
            $("#divChannelContent").html(resp);
            $("#divChannel").slideDown("fast");
            $("#txtSearchChannel").focus();
            Scroll(e);
        }
    });
}

function GetSelectedChannel() {
    if ($("#divSelectedChannelContent").html() == undefined)
        return false;

    var resp = $.ajax({
        url: "../subpages/_SelectedChannel.aspx",
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: true,
        beforeSend: function (resp) {
            $(".loading").slideDown("fast");
        },
        success: function (resp) {
            $(".loading").slideUp("fast");
            $("#divSelectedChannelContent").html(resp);
            $("#divSelectedChannelContent").fadeIn();
        }
    });
}

function InteractivityModerate(element, approved) {
    var idAnswer = $(element).attr("rel");

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=interactivitymoderate&parameters=" + idAnswer + "|" + approved,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;

    var lnkApproved = "#lnkApproved_" + idAnswer;
    var lnkFailed = "#lnkFailed_" + idAnswer;

    if (resp == "True") {
        if (approved) {
            $(lnkApproved).removeClass("unmoderated");
            $(lnkApproved).addClass("moderated");
            $(lnkFailed).removeClass("moderated");
            $(lnkFailed).addClass("unmoderated");
        }
        else {
            $(lnkFailed).removeClass("unmoderated");
            $(lnkFailed).addClass("moderated");
            $(lnkApproved).removeClass("moderated");
            $(lnkApproved).addClass("unmoderated");
        }
    }
    else {
        ShowFailMessage("N&atilde;o foi poss&iacute;vel realizar a modera&ccedil;&atilde;o no momento.");
    }

}

function SaveChannel(idChannel) {
    $("#divSelectedChannelContent").fadeOut("fast");
    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=savecommunitychannel&parameters=" + idChannel,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;

    if (resp == "True") {
        ShowSuccessMessage("Canal relacionado com sucesso.");
        GetSelectedChannel();
    }
    else {
        ShowFailMessage("Erro ao relacionar o canal.")
    }
    $("#divSelectedChannelContent").fadeIn("fast");
}

function RemoveChannel(obj, idChannel) {

    var resp = $.ajax({
        url: "../_AjaxMethods.aspx?function=removecommunitychannel&parameters=" + idChannel,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        async: false
    }).responseText;

    if (resp == "True") {
        ShowSuccessMessage("Canal exclu&iacute;do com sucesso.");
        $(obj).parent().hide("slow");
    }
    else {
        ShowFailMessage("Erro ao excluir o canal.");
    }
}

function FilterList(evt, generalElement, idTextBox, notFoundElement) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 13) {
        return false;
    }
    $(generalElement).hide();

    var text;
    var count = 0;

    $(generalElement).each(function (index, item) {
        text = $(item).text().toUpperCase();
        if (text.indexOf($(":text#" + idTextBox).val().toUpperCase()) != -1) {
            $(item).show();
            count++;
        }
    });
    if (count == 0) {
        $(notFoundElement).show();
    }
    else {
        $(notFoundElement).hide();
    }
    return true;
}

function Scroll(e) {
    //prevent the default action for the click event
    //get the full url - like mysitecom/index.htm#home
    var full_url = e.href;

    //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
    var parts = full_url.split("#");
    var trgt = parts[1];

    //get the top offset of the target anchor
    var target_offset = $("#" + trgt).offset();
    var target_top = target_offset.top;

    //goto that anchor by setting the body scroll top to anchor top
    $('html, body').animate({ scrollTop: target_top }, 500);
}

//Janela Modal
function Modal(id) {
    ShowModal(id);

    $('.window .close').click(function (e) {
        e.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });

    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });
};

function ShowModal(id) {
    //e.preventDefault();

    var id = id;

    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

    $('#mask').fadeIn(1000);
    $('#mask').fadeTo("slow", 0.8);

    //Get the window height and width
    var winH = $(window).height();
    var winW = maskWidth;

    $(id).css('top', winH / 2 - $(id).height() / 2);
    $(id).css('left', (winW - $(id).width()) / 2);
    $(id).css('position', 'fixed');


    $(id).fadeIn(2000);
}


