/**
 * JavaScript main class that is going to be used throughout the application.
 * This should be the base class for Application's JavaScript
 */
var Application = {
	// Collection of functions that will be executed when this script loads
	init: [],

	// Define User Interface related functionalities
	Ui: {},

	// Define general JavaScript utilities
	Util: {
		isDefined: function(obj) { return (typeof(obj) != 'undefined'); },
		isFunction: function(obj) { return jQuery.isFunction(obj); },
		isObject: function(o) { return (o && typeof o == 'object'); },
		isArray: function(o) { return (isObject(o) && o.constructor == Array); },
		submitPost: function(url, parameters) { Application.Util._submitRequest('post', url, parameters); },
		submitGet: function(url, parameters) { Application.Util._submitRequest('get', url, parameters); },
		_submitRequest:					function(method, url, parameters) {
			var form = $('<form method="' + method + '" action="' + url + '" style="display:none;">' + Application.Util._createSubmitRequestData(parameters) + '</form>');
			form.appendTo(document.body);
			form.get(0).submit();
		},
		_createSubmitRequestData:		function(parameters, namePrefix) {
			if(Application.Util.isArray(parameters)) {
				var temp = '';
				if(!namePrefix) namePrefix = 'array';
				for(var i = 0, j = parameters.length; i < j; ++i) {
					temp += Application.Util._createSubmitRequestData(parameters[i], namePrefix + '[' + i + ']');
				}
				return temp;
			} else if(Application.Util.isObject(parameters)) {
				var temp = '';
				if(!namePrefix) namePrefix = '';
				for(var i in parameters) {
					temp += Application.Util._createSubmitRequestData(parameters[i], (namePrefix == ''? i : (namePrefix + '[' + i + ']')));
				}
				return temp;
			} else {
				if(!namePrefix) namePrefix = 'input';
				return '<input type="hidden" name="' + namePrefix + '" value="' + parameters + '" />';
			}
		},
		// Provides XOR encryption/decryption.
		encrypt: function(s, key) {
			var result = '';
			while (key.length < s.length) {
				key += key;
			}
			for (var i=0; i<s.length; i++) {
				result += String.fromCharCode(key.charCodeAt(i)^s.charCodeAt(i));
			}
			return result;
		},
		decrypt: function(s, key) {
			return Application.Util.encrypt(s, key);
		}
	},

	// Define general information
	Info: {
		// Browser sniffing functions
		Browser: {
			_cache: {},
			ie6: function() {
				if(!Application.Util.isDefined(this._cache.ie6))
					this._cache.ie6 = (jQuery.browser.msie && parseFloat(jQuery.browser.version) <= 6);
				return this._cache.ie6;
			}
		}
	},

	// Other miscellaneous functionalities
	Misc: {
		/**
		 * Specify document Min width.
		 * The function can only be called once, subsequent call will be ignored.
		 * @param Integer width Minimum document width
		 * @return void Return nothing
		 */
		specifyDocumentMinWidth: function(width) {
			if(Application.Misc._specifyDocumentMinWidth) return;

			Application.Misc._specifyDocumentMinWidth = {};
			$.extend(Application.Misc._specifyDocumentMinWidth, {
				minwidth:width,
				donotresize:false,
				resize: function() {
					if(Application.Misc._specifyDocumentMinWidth.donotresize) {
						Application.Misc._specifyDocumentMinWidth.donotresize = false;
						return;
					}

					if($(document.body).width() < this.minwidth) {
						$(document.body).css('width', Application.Misc._specifyDocumentMinWidth.minwidth+'px');
						Application.Misc._specifyDocumentMinWidth.donotresize = true;
					} else $(document.body).css('width', 'auto');
				},
				eventDOMReady: function(event) {
					if($.browser.msie && parseInt($.browser.version) == 6) {
						$(window).resize(Application.Misc._specifyDocumentMinWidth.eventWindowResize);
						Application.Misc._specifyDocumentMinWidth.resize();
					} else $(document.body).css('min-width', Application.Misc._specifyDocumentMinWidth.minwidth+'px');
				},
				eventWindowResize: function(event) { Application.Misc._specifyDocumentMinWidth.resize(); }
			});

			Application.init.push(Application.Misc._specifyDocumentMinWidth.eventDOMReady);
		},

		/**
		 * Ping the server on an interval basis.
		 * The function can only be called once, subsequent call will be ignored.
		 * @param String url The url to be ping
		 * @param Integer interval The interval server needs to be ping against in seconds
		 * @param Boolean post Specify to use POST method instead of GET (OPTIONAL, default FALSE)
		 * @param Object data Data to be passed to the URL (OPTIONAL, default NOTHING)
		 * @return void Return nothing
		 */
		 setPingServer: function(url, interval, post, data) {
		 	if(Application.Misc._setPingServer) return;

		 	Application.Misc._setPingServer = {};
		 	$.extend(Application.Misc._setPingServer, {
		 		interval:interval,
		 		url:url,
		 		post:!!post,
		 		data:(data || {}),
		 		eventDOMReady: function(event) { setInterval("Application.Misc._setPingServer.pingServer();", Application.Misc._setPingServer.interval); },
		 		pingServer: function() {
		 			if(Application.Misc._setPingServer.url == '') return;
		 			if(Application.Misc._setPingServer.post) $.post(Application.Misc._setPingServer.url, data);
		 			else $.get(Application.Misc._setPingServer.url, data);
		 		}
		 	});

		 	Application.init.push(Application.Misc._setPingServer.eventDOMReady);
		 }
	},

	// Provides a place holder for page specific code
	Page: {},

	// Provides a placeholder for modules (so that you can extends the script)
	Modules: {},

	WEB: {
	 WebMethodExec: function(pagePath, fn, paramArray, successFn, errorFn) {
            var paramList = '';
            if (paramArray.length > 0) {
                for (var i = 0; i < paramArray.length; i += 2) {
                    if (paramList.length > 0) paramList += ',';
                    paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
                }
            }
            paramList = '{' + paramList + '}';

            $.ajax({
                type: "POST",
                url: pagePath + "/" + fn,
                contentType: "application/json; charset=utf-8",
                data: paramList,
                success: successFn,
                error: errorFn,
                async: false
            });
        }
    },
	
	Datetime: {
            convert: function(d) {
                return (
                    d.constructor === Date ? d :
                    d.constructor === Array ? new Date(d[0], d[1], d[2]) :
                    d.constructor === Number ? new Date(d) :
                    d.constructor === String ? new Date(d) :
                    typeof d === "object" ? new Date(d.year, d.month, d.date) :
                    NaN
                );
            },
            compare: function(a, b) {
                return (
                    isFinite(a = this.convert(a).valueOf()) &&
                    isFinite(b = this.convert(b).valueOf()) ?
                    (a > b) - (a < b) :
                    NaN
                );
            },
            inRange: function(d, start, end) {
                return (
                    isFinite(d = this.convert(d).valueOf()) &&
                    isFinite(start = this.convert(start).valueOf()) &&
                    isFinite(end = this.convert(end).valueOf()) ?
                    start <= d && d <= end :
                    NaN
                );
            },
            isValidDate: function(d, m, y) {
                    date = new Date();
                    m = m - 1; 
                    date.setFullYear(y, m, d);
                    return (m == date.getMonth());
            }
        },


	WYSIWYGEditor: {
		getContent: function() {
			return tinyMCE.activeEditor.getContent();
		},
		setContent: function(content) {
			tinyMCE.activeEditor.setContent(content);
		},
		isWysiwygEditorActive: function() {
			if (typeof(tinyMCE) != 'undefined') {
				return true;
			}
			return false;
		},
		insertText: function(text) {
			tinyMCE.activeEditor.execCommand('mceInsertContent',false, text);
		}
	},


	// Function that handle on DOM ready event
	eventDocumentReady: function(event) {
		for(var i = 0, j = Application.init.length; i < j; ++i)
			if(jQuery.isFunction(Application.init[i])) Application.init[i]();
	}
};

// This will initialize JavaScript main application when document is loaded
// Requires jQuery to be defined first...
$(document).one('ready', Application.eventDocumentReady);
/**
 * -----
 */




/**
 * Ui.HelpToolTip
 */
if(!Application.Ui._) Application.Ui._ = {};
Application.Ui._.HelpToolTip = {
	eventDOMReady: function(event) {
		var elm = $('span.HelpToolTip');
		for(var i = 0, j = elm.size(); i < j; ++i) {
			var helpTitle = $('span.HelpToolTip_Title', elm.get(i)).html();
			var helpContents = $('span.HelpToolTip_Contents', elm.get(i)).html();

			$(elm.get(i)).bind('mouseover', {'title':helpTitle, 'contents':helpContents}, Application.Ui._.HelpToolTip.eventOnMouseOver);
			$(elm.get(i)).mouseout(Application.Ui._.HelpToolTip.eventOnMouseOut);
		}
	},

	eventOnMouseOver: function(event) {
		$('<div class="HelpToolTip_Placeholder" style="display:inline; position: absolute; width: 240px; background-color: #FEFCD5; border: solid 1px #E7E3BE; padding: 10px;">'
			+ '<span class="helpTip"><b>' + event.data.title + '</b></span>'
			+ '<br /><img src="images/1x1.gif" width="1" height="5" />'
			+ '<br /><div style="padding-left: 10px; padding-right: 5px;">' + event.data.contents + '</div>'
			+ '</div>').appendTo(this);
	},

	eventOnMouseOut: function(event) { $('div.HelpToolTip_Placeholder', this).remove(); }
};

Application.Ui.HelpToolTip = function(selector, title, contents) {
	$(selector).bind('mouseover', {'title':title, 'contents':contents}, Application.Ui._.HelpToolTip.eventOnMouseOver);
	$(selector).mouseout(Application.Ui._.HelpToolTip.eventOnMouseOut);
};

// Add to initialization procedure to convert all span elements that have "HelpToolTip" as one of their class to be converted
Application.init.push(Application.Ui._.HelpToolTip.eventDOMReady);
/**
 * -----
 */



function inArray(id, arraylist, returnvalue) {
	for (alitem = 0; alitem < arraylist.length; alitem++) {
		val = arraylist[alitem].toString();
		if (id == val) {
			if (returnvalue)
			{
				return alitem;
			}
			return true;
		}
	}

	if (returnvalue)
	{
		return -1;
	}
	return false;
}



function getIFrameDocument(aID){
	// if contentDocument exists, W3C compliant (Mozilla)
	if (document.getElementById(aID).contentDocument){
		return document.getElementById(aID).contentDocument;
	} else {
		// IE
		return document.frames[aID].document;
	}
}



// Used in text areas to make sure text is inserted into the Text area
function insertAtCursor(myField, myValue) {
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	} else {
		if (myField.selectionStart || myField.selectionStart == '0') {
			var startPos = myField.selectionStart;
			var endPos = myField.selectionEnd;
			myField.value = myField.value.substring(0, startPos)
				+ myValue
				+ myField.value.substring(endPos, myField.value.length);
		} else {
			myField.value += myValue;
		}
	}
}


Array.prototype.compareArrays = function(arr) {
	if (this.length != arr.length) return false;
	for (var i = 0; i < arr.length; i++) {
		if (this[i].compareArrays) { //likely nested array
			if (!this[i].compareArrays(arr[i])) return false;
			else continue;
		}
		if (this[i] != arr[i]) return false;
	}
	return true;
}


function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}


function toggleAllCheckboxes(check)
{
	formObj = check.form;
	for (var i=0;i < formObj.length; i++) {
		fldObj = formObj.elements[i];
		if (fldObj.type == 'checkbox') {
			fldObj.checked = check.checked;
		}
	}
}




function CheckRadio(Id)
{
	return ($('form input[id^=' + Id + ']:radio:checked').size() > 0);
}

function CheckMultiple(name, frm) {
	return ($("input[@name^='" + name + "']:checked", (frm || document)).size() != 0);
}

/**
 * Returns true if the d/m/y is a valid date.
 */
function isValidDate(d, m, y)
{
	date = new Date();
	m = m - 1; // months start at 0
	date.setFullYear(y, m, d);
	return (m == date.getMonth());
}

/**
 * Validates a custom date field. Returns true if it has a valid date or is left empty.
 */
function CheckDate(field)
{
	date_fields = jQuery.map(["dd", "mm", "yy"], function(el, i) { return document.getElementById(field + "[" + el + "]"); } );
	error = false;
	all_blank = true;
	for (i = date_fields.length-1; i >= 0; i--) {
		if (date_fields[i].value == "") {
			error = true
			date_fields[i].focus();
		} else {
			all_blank = false;
		}
	}
	return all_blank || (!error && isValidDate(date_fields[0].value, date_fields[1].value, date_fields[2].value));
}

/**
 * Returns true if str is a (roughly) valid email address.
 */
function isValidEmail(str)
{
	// We use a simple pattern here because the server side check is complex
	// and we don't want to exclude stuff it will accept.
	if(str.indexOf('@') > -1 && str.indexOf('.') > -1) {
		return true;
	}

	return false;
}

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function decode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	do {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));

		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		output = output + String.fromCharCode(chr1);

		if (enc3 != 64) {
			output = output + String.fromCharCode(chr2);
		}

		if (enc4 != 64) {
			output = output + String.fromCharCode(chr3);
		}
	} while (i < input.length);
	return output;
}


function stripHTML(html) {
    var BodyContents = /([\s\S]*\<body[^\>]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i;
    var h = html.match(BodyContents);
    if (h != null && h[2]) {
        html = h[2];
    }
    html = html.replace(/\/\/--\>/gi, "");
    html = html.replace(/<br\/?>/gi, "\n");
    html = html.replace(/(<\/h.>|<\/p>|<\/div>)/gi, "$1\n\n");
    html = html.replace(/<[^>]+>/g, "");
    html = html.replace(/&lt/g, "<");
    html = html.replace(/&gt/g, ">");
    html = html.replace(/&nbsp/g, "");
    html = html.replace(/&#160/g, "");
    return html;

}


function HtmlToTextArea(html) {
    var BodyContents = /([\s\S]*\<body[^\>]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i;
    var h = html.match(BodyContents);
    if (h != null && h[2]) {
        html = h[2];
    }

    html = html.replace(/<br\/?>/gi, "\n");

    return html;
}


function stripHTMLOnSubmit() {
    var re = /<\S[^><]*>/g
    for (i = 0; i < arguments.length; i++)
        arguments[i].value = arguments[i].value.replace(re, "")
}

function stripHTMLWithLinks(c) {
	var BodyContents = /([\s\S]*\<body[^\>]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i ;
	var h = c.match(BodyContents);
	if (h != null && h[2]) {
		c = h[2];
	}
	c = c.replace(/<a\s.*?href\s*=\s*"(.*?)".*?>(.*?)<\/a>/gi, "$2 [$1]");
	c = c.replace(/<a\s.*?href\s*=\s*'(.*?)'.*?>(.*?)<\/a>/gi, "$2 [$1]");
	c = c.replace(/\/\/--\>/gi, "");
	c = c.replace(/(\n)/gi,"");
	c = c.replace(/(\r)/gi,"");
	c = c.replace(/<title[^\>]*\>[\s\S]*\<\/title\>/gi,"");
	c = c.replace(/<br\s*\/\s*>/gi,"\n");
	c = c.replace(/(<\/h.>|<\/p>|<\/div>)/gi, "$1\n\n");
	c = c.replace(/<[^>]+>/g,"");
	c = c.replace(/&lt;/g,"<");
	c = c.replace(/&gt;/g,">");
	c = c.replace(/&nbsp;/g," ");
	return c;
}


function grabTextContent(textareaname, editorname) {
	try
	{
		var strip = '';
		if ( Application.WYSIWYGEditor.isWysiwygEditorActive() ) {
			strip = Application.WYSIWYGEditor.getContent();
		} else {
			strip = document.getElementById(editorname + '_html').value;
		}
		strip = stripHTMLWithLinks(strip);
		document.getElementById(textareaname).value = strip;
	}
	catch (error)
	{
	}
}


function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

hexdig='0123456789ABCDEF';
function Dec2Hex(d) {
	return hexdig.charAt((d-(d%16))/16)+hexdig.charAt(d%16);
}

function RGB2Hex(r,g,b) {
	return Dec2Hex(r)+Dec2Hex(g)+Dec2Hex(b);
}

function Hex2Dec(h) {
	h=h.toUpperCase();
	d=0;
	for (i=0;i<h.length;i++) {
		d=d*16;
		d+=hexdig.indexOf(h.charAt(i));
	}
	return d;
}




/**
 * Prototype String function to include trim()
 * The trim function will strip leading and trailing whitespaces from string
 */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }


function isObject(o) { return (o && typeof o == 'object'); }
function isArray(o) { return (isObject(o) && o.constructor == Array); }


/**
* Check if the user agent is IE 6
*
* @return bool True if it's IE6, false if it's not
*/
function isIE6()
{
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);

	if(browser == 'Microsoft Internet Explorer' && version <= 6) {
		return true;
	}
}


/**
* These functions escape and unescape HTML
*/

function escapeHTML(text) {
	return text
		.replace(/&/g,"&amp;")
		.replace(/</g,"&lt;")
		.replace(/>/g,"&gt;");
}
function unescapeHTML(text) {
	return text
		.replace(/&gt;/g,">")
		.replace(/&lt;/g,"<")
		.replace(/&amp;/g,"&");
}




/**
* Extensoes do JQuery
*/

//Valida email
jQuery.fn.isValidEmail = function() {
    var str = $(this).val();

    if (str.indexOf('@') > -1 && str.indexOf('.') > -1) {
        return true;
    }

    return false;
}

function isValidEmail(email) {
    if (email.indexOf('@') > -1 && email.indexOf('.') > -1)
        return true;

    return false;
}

//Pega valor de uma CheckBox
jQuery.fn.isChecked = function() {
    this.each(function() {
        isChecked = this.checked;
    });

    return isChecked;
}

jQuery.fn.encHTML = function() {
    return this.each(function() {
        var me = jQuery(this);
        var html = me.html();
        me.html(html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'));
    });
};

jQuery.fn.decHTML = function() {
    return this.each(function() {
        var me = jQuery(this);
        var html = me.html();
        me.html(html.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
    });
};

jQuery.fn.isEncHTML = function(str) {
    if (str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1)
        return true;
    else
        return false;
};

jQuery.fn.decHTMLifEnc = function() {
    return this.each(function() {
        var me = jQuery(this);
        var html = me.html();
        if (jQuery.fn.isEncHTML(html))
            me.html(html.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
    });
}



function strReplaceChr(texto) {

    texto = texto.replace(/[^a-zA-Z 0-9]+/g, '');
    texto = texto.replace(/\s * | * \s+/g, '');

    //

    return $.trim(texto);
}

function validacpf(s) {

    s = s.replace(/[^0-9]/g, "");

    var i;
    var c = s.substr(0, 9);
    var dv = s.substr(9, 2);
    var d1 = 0;

    for (i = 0; i < 9; i++) {
        d1 += c.charAt(i) * (10 - i);
    }

    if (d1 == 0)
        return false;


    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(0) != d1)
        return false;

    d1 *= 2;

    for (i = 0; i < 9; i++) {

        d1 += c.charAt(i) * (11 - i);

    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(1) != d1)
        return false;

    return true;

}



function validaFeb(date) {
    date = date.split('/');
    year = date[2];

    test = false;

    if (date[1] == 2) {
        if (year % 100 == 0) {
            if (year % 400 == 0)
                test = true;
        }
        else
            if ((year % 4) == 0)
            test = true;
        else
            test = false;

        if (test == true)
            if (date[0] > 29) return false;
        else
            return true;

        if (test == false)
            if (date[0] > 28) return false;
        else
            return true;
    } else return true;
}



function onlyNum(e) {
    var key = new Number();
    if (window.event) {
        key = e.keyCode;
    }
    else if (e.which) {
        key = e.which;
    }
    else {
        return true;
    }
    if ((key < 48) || (key > 63) && (key == 8)) {
        return false;
    }
}


function setMaxLength() {
    var x = document.getElementsByTagName('textarea');
    var counter = document.createElement('div');
    counter.className = 'counter';



    for (var i = 0; i < x.length; i++) {
        if (x[i].getAttribute('MaxLen')) {
            x[i].onkeyup = x[i].onchange = checkMaxLength;
            x[i].onkeyup();
        }
    }
}

function checkMaxLength() {
    var maxLength = this.getAttribute('MaxLen');
    var currentLength = this.value.length;
    if (currentLength > maxLength) {
        this.value = this.value.substring(0, maxLength)
    }
}


function somenteNumero(txt) {
    var anum = /(^\d+$)|(^\d+\.\d+$)/;
    return anum.test(txt);
}

function htmlToTextArea(html) {
    var BodyContents = /([\s\S]*\<body[^\>]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i;
    var h = html.match(BodyContents);
    if (h != null && h[2]) {
        html = h[2];
    }

    html = html.replace(/<br\/?>/gi, "\n");

    return html;
}