﻿// Core functions

function $() {
//	return _$.apply(null, [document].concat(arguments));
	if (arguments.length == 1) {
		var element = arguments[0];
		if (typeof(element) == "string")
			return document.getElementById(element);
		else
			return element;
	} else {
		var args = $A(arguments);
		return args.map(function(element) { return $(element) });
	}
}

function _$() {
	var doc = arguments[0];
	if (arguments.length == 2) {
		var element = arguments[1];
		if (typeof(element) == "string")
			return doc.getElementById(element);
		else
			return element;
	} else {
		var args = $A(arguments).slice(1);
		return args.map(function(element) { return _$(doc, element) });
	}
}

function $A(list) {
	var result = [];
	for (var i = 0; i < list.length; i++)
		result.push(list[i]);
	return result;
}

function $T(element) {
	element = $(element);
	return element ? (element["textContent"] || element["innerText"]) : null;
}

function getElementsByClass(searchClass, node, tag) {
	var classElements = [];
	if (!node)
		node = document;
	if (!tag)
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function loadCSS(url) {
	var css = document.createElement("LINK");
	css.type = "text/css";
	css.rel = "stylesheet";
	css.href = url;
	document.getElementsByTagName("HEAD")[0].appendChild(css);
}

function loadScript(url) {
	var element = document.createElement("script");
	element.type = "text/javascript";
	element.src = url;
	document.getElementsByTagName("head")[0].appendChild(element);
}

function $SPF(title) {
	var elements = document.getElementsByTagName("*");
	var i = Array.prototype.indexByAttribute.call(elements, "title", title);
	if (i != -1)
		return elements[i];
	else
		return null;
}

function getModuleOption(module, key, default_value) {
	var value;
	if (window[module] && window[module]["options"]) {
		value = window[module]["options"][key];
	}
	return value == undefined ? default_value : value;
}

function setModuleOption(module, key, value) {
	if (!window[module])
		window[module] = {};
	if (!window[module]["options"])
		window[module]["options"] = {};
	window[module]["options"][key] = value;
}

function getBrowserLanguage() {
	return navigator.language ? navigator.language : navigator.userLanguage;
}

function getOKButtons(doc) {
	doc = doc ? doc : document;
	return getChildrenElements(doc, byAttribute("value", "OK"));
//	return getElementsByAttribute("value", "OK", "INPUT");
}

function getCancelButtons(doc) {
	doc = doc ? doc : document;
	return getChildrenElements(doc, byAttribute("value", "Cancelar"));
//	return getElementsByAttribute("value", "Cancelar", "INPUT");
}

function getElementsByAttribute(key, value, tag) {
	tag = tag ? tag : "*";
	var elements = $A(document.getElementsByTagName(tag));
	return elements.filterByAttribute(key, value);
}

function attachFunctionBefore(obj, key, handler) {
	var currentHandler = obj[key];
	obj[key] = function() {
		handler.apply(this, arguments);
		if (currentHandler)
			return currentHandler.apply(this, arguments);
	};
}

function attachFunctionAfter(obj, key, handler) {
	var currentHandler = obj[key];
	obj[key] = function() {
		var result;
		if (currentHandler)
			result = currentHandler.apply(this, arguments);
		handler.apply(this, arguments);
		return result;
	};
}

function addEvent(obj, type, fn) {
	if (obj.attachEvent) {
		obj['e' + type + fn] = fn;
		obj[type + fn] = function() { obj['e' + type + fn](window.event) };
		obj.attachEvent('on' + type, obj[type + fn]);
	} else
		obj.addEventListener(type, fn, false);
}

function removeEvent(obj, type, fn) {
	if (obj.detachEvent) {
		obj.detachEvent('on' + type, obj[type + fn]);
		obj[type + fn] = null;
	} else
		obj.removeEventListener(type, fn, false);
}

function absoluteTop(obj) {
	var top = 0;
	while (obj) {
		top += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return top;
}

function absoluteLeft(obj) {
	var left = 0;
	while (obj) {
		left += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return left;
}

function absoluteBottom(obj) {
	return absoluteTop(obj) + obj.offsetHeight;
}

function absoluteRight(obj) {
	return absoluteLeft(obj) + obj.offsetWidth;
}

function encodeUTF8(s) {
	return unescape(encodeURIComponent(s));
}

function decodeUTF8(s) {
	return decodeURIComponent(escape(s));
}

function decodeMOSS(s) {
	return decodeUTF8(unescape(s));
}

function embedElement(child, tag) {
	var newParent = document.createElement(tag);
	child.parentNode.insertBefore(newParent, child);
	newParent.appendChild(child);
	return newParent;
}

function scribdLink(url) {
	var link = 'http://www.scribd.com/slurp?scribd_publisher_id=pub-61006514222715624584&display_mode=fullscreen&public=false&url=' + escape(url);
	return link;
}

function fullLocationHost() {
	return window.location.protocol + "//" + window.location.host;
}

function iframeDocument(iframe) {
/*
  if (IFrameObj.contentDocument) {
    // For NS6
    IFrameDoc = IFrameObj.contentDocument; 
  } else if (IFrameObj.contentWindow) {
    // For IE5.5 and IE6
    IFrameDoc = IFrameObj.contentWindow.document;
  } else if (IFrameObj.document) {
    // For IE5
    IFrameDoc = IFrameObj.document;
*/
/*
	if (!iframe)
		return null;
		
	if (iframe["contentDocument"])
		return iframe.contentDocument;
	else if (iframe["document"])
		return iframe.document;
	else if (iframe["contentWindow"])
		return iframe.contentWindow.document;
	else
		return null;
*/
	return iframe.contentWindow.document;
}

function iframeBody(iframe) {
	var doc = iframeDocument(iframe);
	return doc.documentElement ? doc.documentElement : doc.body;
}

function createIframe(onloadHandler) {
	var div = document.createElement("DIV");
	var id = (new Date()).getTime().toString();
	var frameId = "frame_" + id;
	var handlerName = "handle_" + id;
	
	window[handlerName] = onloadHandler;
	div.innerHTML = "<iframe style='width: 0px; height: 0px;' frameborder='0' onload='" + handlerName + "(this)' id='" + frameId + "'></iframe>";
	document.body.appendChild(div);
	return frameId;
}

function scrollbarWidth() {
	document.body.style.overflow = 'hidden';
	var width = document.body.clientWidth;
	document.body.style.overflow = 'scroll';
	width -= document.body.clientWidth;
	if (!width)
		width = document.body.offsetWidth - document.body.clientWidth;
	document.body.style.overflow = '';
	return width;
}

function autosizeIframe(iframe) {
	var extra = 1;//scrollbarWidth();
	var body = iframeDocument(iframe).body;

	var width = body.scrollWidth + extra;
	iframe.style.width = width + "px";

	var height = body.scrollHeight + extra;
	iframe.height = height;
}

function buildFormHTML(url, names, method) {
	method = method ? method : "POST";
	var fields = names.map(
		function(name) {
			return "<input name='" + name + "' id='" + name + "' type='hidden' />";
		}
	);
	return "<form action='" + url + "' method='" + method + "'>" + fields.join("\n") + "</form>";
}

function IframeSimpleRequest(url) {
	this.url = url;
	this.state = "empty";

	var request = this;
	this.iframeId = createIframe(
		function(thisFrame) {
			if (request.state == "get" && request.handleResult) {
				request.handleResult(iframeDocument(thisFrame), thisFrame);
			}
		}
	);
}

IframeSimpleRequest.prototype.send = function(handleResult) {
	this.handleResult = handleResult;

	this.state = "get";
	var iframe = $(this.iframeId);
	iframeNavigate(iframe, this.url);
}

function IframeRequest(url, names, method) {
	this.url = url;
	this.names = names;
	this.method = method ? method : "GET";
	
	this.state = "empty";

	var request = this;
	this.iframeId = createIframe(
		function(thisFrame) {
			if (request.state == "form") {
				request.state = "fill";
				request.fillValues();
				iframeDocument(thisFrame).forms[0].submit();
			} else if (request.state == "fill" && request.handleResult)
				request.handleResult(iframeDocument(thisFrame), thisFrame);
		}
	);
}

IframeRequest.prototype.send = function(values, handleResult) {
	this.values = values;
	this.handleResult = handleResult;

	var iframe = $(this.iframeId);
	var formName = "form_" + this.iframeId;
	this.state = "form";
	iframeNavigate(
		iframe,
		appendParameters(["action", "method", "nome", "campos"], [this.url, this.method, formName, this.names.join(",")], "http://argus.iica.ac.cr:19555/scripts/cria_form.aspx")
	);
}

IframeRequest.prototype.fillValues = function() {
	var doc = iframeDocument($(this.iframeId));
	for (var i = 0; i < this.names.length; i++) {
		var input = _$(doc, this.names[i]);
		input.value = this.values[i];
	}
}

function waitReady(obj, key, func) {
	var timer = setInterval(
		function() {
			if (obj[key] != undefined) {
				clearInterval(timer);
				func(obj[key], obj, key);
			}
		},
		100
	);
}

function onDOMReady(fn, doc)
{
	doc = doc ? doc : document;

	//W3C
	if(doc.addEventListener)
	{
		doc.addEventListener("DOMContentLoaded", fn, false);
	}
	//IE
	else
	{
		doc.onreadystatechange = function() {
			if(doc.readyState == "interactive")
			{
				fn();
			}
		};
	}
}

function prependElement(element, child) {
	return element.insertBefore(child, element.firstChild);
}

function insertAfter(parentElement, newElement, referenceElement)
{
	return parentElement.insertBefore(newElement, newElement.nextSibling);
}

function insertSiblingAfter(element, newSibling) {
	return element.parentNode.insertAfter(newSibling, element);
}

function insertSiblingBefore(element, newSibling) {
	return element.parentNode.insertBefore(newSibling, element);
}

function parentByTag(child, tag) {
	var parent = child.parentNode;
	while (parent != document && !tag.test(parent.nodeName))
		parent = parent.parentNode;
	return tag.test(parent.nodeName) ? parent : null;
}

function getParentElement(child, pattern) {
	var parent = child.parentNode;
	while (parent != document && !pattern.test(parent))
		parent = parent.parentNode;
	return pattern.test(parent) ? parent : null;
}

function isParentElement(parentCandidate, child) {
	var parent = child.parentNode;
	while (parent != document && parent != parentCandidate)
		parent = parent.parentNode;
	return parent == parentCandidate;
}

function getChildrenElements(parent, pattern, stopAtMatchingLevel) {
	if (!parent || !parent["childNodes"])
		return [];
		
	var children = $A(parent.childNodes);
	var result = [];
	while (children.length > 0) {
		var child = children.shift();
		
		if (pattern.test(child))
			result.push(child);

		var mustStop = (result.length > 0) && stopAtMatchingLevel;
		if (!mustStop && child.childNodes)
			Array.prototype.push.apply(children, $A(child.childNodes));
	}
	return result;
}

function iframeNavigate(iframe, url) {
	iframeDocument(iframe).location.replace(url);
}

function getChildElement(parent, pattern) {
	for (var i = 0; i < parent.childNodes.length; i++) {
		var child = parent.childNodes[i];
		if (pattern.test(child))
			return child;
		if (child["childNodes"]) {
			var result = getChildElement(child, pattern);
			if (result)
				return result;
		}
	}
	return null;
/*
	var children = $A(parent.childNodes);
	var result = [];
	while (children.length > 0) {
		var child = children.shift();
		
		if (pattern.test(child))
			return child;

		if (child.childNodes)
			Array.prototype.push.apply(children, $A(child.childNodes));
	}
	return null;
*/
}

function getEditFormElement(title) {
	return getChildElement(
		document,
		function(element) {
			return /INPUT|SELECT|TEXTAREA/.test(element.tagName) && title.test(element["title"]);
		}
	);
//	return getChildrenElements(document, byTagName(/INPUT|SELECT|TEXTAREA/)).first(byAttribute("title", title));
}

function getEditFormTD(title) {
	var element = getEditFormElement(title);
	return element ? getParentElement(element, byTagName("TD")): null;
}

function getEditFormTR(title) {
	var td = getEditFormTD(title);
	return td ? getParentElement(td, byTagName("TR")): null;
}

function getFormTable(doc) {
	doc = doc ? doc : document;
	return getChildElement(doc, byClass("ms-formtable"));
}

function getPreviousSibling(element, pattern) {
	var result = element.previousSibling;
	while (result && !pattern.test(result))
		result = result.previousSibling;
	return result;
}

function getNextSibling(element, pattern) {
	var result = element.nextSibling;
	while (result && !pattern.test(result))
		result = result.nextSibling;
	return result;
}

function byId(name) {
	return function(element) {
		return element ? name.test(element.id) : false;
	};
}

function byTagName(name) {
	return function(element) {
		return element ? name.test(element.tagName) : false;
	};
}

function byTitle(name) {
	return function(element) {
		return element ? name.test(element.title) : false;
	};
}

function byClass(name) {
/*
	var pattern = new RegExp('(^|\\\\s)' + name + '(\\\\s|$)');
	return function(element) {
		return pattern.test(element.className);
	};
*/
	return function(element) {
		return (element && element["className"]) ? $A(element.className.split(/\s+/)).some(name) : false;
	};
}

function childrenByTag(parent, tag) {
	var children = $A(parent.childNodes);
	var result = [];
	while (children.length > 0) {
		var child = children.shift();
		
		if (tag.test(child.nodeName))
			result.push(child);
		
		Array.prototype.push.apply(children, $A(child.childNodes));
	}
	return result;
}

function selectByValue(select, value) {
	var i = $A(select.options).indexByAttribute("value", value);
	if (i != -1)
		select.selectedIndex = i;
}

function zipObject(keys, values, result) {
	if (!result)
		result = {};
	for (var i = 0; i < keys.length; i++)
		result[keys[i]] = values[i];
	return result;
}


function showElement(element) {
	if (getObjectClass(element) == "Array") {
		element.forEach(showElement);
		return;
	}
		
	setElementVisible(element, true);
}

function hideElement(element) {
	if (getObjectClass(element) == "Array") {
		element.forEach(hideElement);
		return;
	}
	
	setElementVisible(element, false);
}

function setElementVisible(element, visible, visibleValue) {
	visibleValue = visibleValue ? visibleValue : "";
	if (element && element["style"])
		element.style.display = visible ? visibleValue : "none";
}

function isElementVisible(element) {
	if (element && element["style"])
		return element.style.display != "none";
	else
		return false;
}

function toggleElement(element) {
	if (isElementVisible(element))
		hideElement(element);
	else
		showElement(element);
}

function hideAll(idList) {
	idList.forEach(
		function(id) {
			hideElement($(id))
		}
	);
}

function showOnlyElement(selected, idList) {
	idList.forEach(
		function(id) {
			setElementVisible($(id), selected.test(id), "block");
		}
	);
}

// SharePoint functions

function muda_pais(nome) {
	SetCookie("pais", nome, "/");
	window.location.reload(true);
}

function pega_pais_atual() {
	var selecionado = GetCookie("pais");
	return selecionado ? selecionado : "Brasil";
}

function pega_titulo_pagina() {
	var titulo = $T(getChildElement(document, byClass("breadcrumbCurrent")));
	titulo = titulo ? titulo : document.title;
	return titulo;
}

function recomenda_pagina(todos) {
	var titulo = document.title;//pega_titulo_pagina();
	
	var idioma = (GetCookie("idioma") == "es") ? ".es" : "";
	var url_recomende = appendParameters(["titulo", "url"], [titulo, document.URL.toString()], "/Paginas/Recomende" + idioma + ".aspx");
	if (todos)
		url_recomende += "&" + encodeParameters(["destinatario"], ["todos"]);

	STSNavigate(url_recomende);
}

function arruma_titulo_pagina(titulo) {
	document.title = titulo ? titulo : pega_titulo_pagina();
}

// soh encontra qdo titulo esta visivel
function encontra_webpart(titulo) {
  var lista_td = document.getElementsByTagName("TD");
  for (var i = 0; i < lista_td.length; i++) {
    var candidato = lista_td[i];
    if (/^WebPartTitle/.test(candidato.id)) {
      if (titulo.test($T(candidato)) || titulo.test(candidato.title)) {
        var tabela_titulo = parentByTag(candidato, "TABLE");
        var tabela_webpart = parentByTag(tabela_titulo, "TABLE");
        return tabela_webpart;
      }
    }
  }
  return null;
}

function getTableContent(table) {
	return getChildElement(table, byTagName("TBODY"));
}

function setLookupFromFieldName(fieldName, value) {

  if (value == undefined) return;

  var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);

 

// if theSelect is null, it means that the target list has more than

// 20 items, and the Lookup is being rendered with an input element

 

  if (theSelect == null) {

    var theInput = getTagFromIdentifierAndTitle("input","",fieldName);

    ShowDropdown(theInput.id); //this function is provided by SharePoint

    var opt=document.getElementById(theInput.opt);

    setSelectedOption(opt, value);

    OptLoseFocus(opt); //this function is provided by SharePoint

  } else {

    setSelectedOption(theSelect, value);

  }

}

 

function setSelectedOption(select, value) {

  var opts = select.options;

  var l = opts.length;

  if (select == null) return;

  for (var i=0; i < l; i++) {

    if (opts[i].value == value) {

      select.selectedIndex = i;

      return true;

    }

  }

  return false;

}

 

function getTagFromIdentifierAndTitle(tagName, identifier, title) {

  var len = identifier.length;

  var tags = document.getElementsByTagName(tagName);

  for (var i=0; i < tags.length; i++) {

    var tempString = tags[i].id;

    if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {

      return tags[i];

    }

  }

  return null;

}

// Callbacks

_callbacks = {}

function registerCallback(name, func) {
  if (_callbacks[name])
    _callbacks[name].push(func);
  else
    _callbacks[name] = [func];
}

function registerUniqueCallback(name, func) {
  _callbacks[name] = [func];
}

function dispatchCallbacks(name) {
  if (_callbacks[name]) {
    var callbacks = _callbacks[name];
    for (var i = 0; i < callbacks.length; i++)
      callbacks[i]($(name));
  }
}

// HTTP

function encodeParameters(names, values) {
	var params = [];
	for (var i = 0; i < names.length; i++)
		params.push(names[i] + "=" + encodeURIComponent(values[i]));
	return params.join("&");
}

function decodeParameters(data) {
	var result = {};
	data = data ? data : window.location.search.slice(1);
	var params = data.split("&");
	for (var i = 0; i < params.length; i++) {
		var parts = params[i].split("=");
		result.pushValue(decodeURIComponent(parts[0]), decodeURIComponent(parts[1]));
	}
	return result;
}

function getDecodedParameter(name, default_value) {
	var param;

	var param_values = decodeParameters()[name];
	if (param_values && param_values.length > 0)
		param = param_values[0];
	return (param != undefined) ? param : default_value;
}

function appendParameters(names, values, current) {
	current = current ? current : window.location.href;
	if (!current.contains("?"))
		current += "?";
	if (!current.contains("&"))
		current += "&";
	return current + encodeParameters(names, values);
}

// Templates

function applyTemplate(template, values) {
	for (var name in values) {
		template = template.replace(new RegExp("[$]" + name.toUpperCase(), "g"), values[name]);
	}
	return template;
}

// Core extensions
//-/***
Array.prototype.every = function(pattern) {
	for (var i = 0; i < this.length; i++) {
		if (!pattern.test(this[i], i))
			return false;
	}
	return true;
}


Array.prototype.some = function(pattern) {
	for (var i = 0; i < this.length; i++) {
		if (pattern.test(this[i], i))
			return true;
	}
	return false;
}

Array.prototype.filter = function(pattern) {
	var result = [];
	for (var i = 0; i < this.length; i++) {
		var item = this[i];
		if (pattern.test(item, i))
			result.push(item);
	}
	return result;
}

Array.prototype.filterByAttribute = function(key, value) {
	return this.filter(function(item, i) { return value.test(item[key], i) });
}

//-***/

Array.prototype.forEach = function(func) {
	for (var i = 0; i < this.length; i++)
		func(this[i], i);
}

//-/**
Array.prototype.indexByAttribute = function(key, value) {
	for (var i = 0; i < this.length; i++) {
		if (value.test(this[i][key], i))
			return i;
	}
	return -1;
}

Array.prototype.indexOf = function(pattern) {
	for (var i = 0; i < this.length; i++) {
		if (pattern.test(this[i], i))
			return i;
	}
	return -1;
}

Array.prototype.map = function(func) {
	var result = [];
	for (var i = 0; i < this.length; i++)
		result.push(func(this[i], i));
	return result;
}

Array.prototype.contains = function(other) {
	return this.indexOf(other) != -1;
}

Array.prototype.first = function(pattern) {
	for (var i = 0; i < this.length; i++) {
		if (pattern.test(this[i], i))
			return this[i];
	}
	return undefined;
}

Array.prototype.last = function(pattern) {
	for (var i = this.length - 1; i > 0; i--) {
		if (pattern.test(this[i], i))
			return this[i];
	}
	return undefined;
}

function byAttribute(key, value) {
	return function(item, i) {
		return value.test(item[key], i);
	};
}

function toAttribute(key) {
	return function(item) {
		return item[key];
	}
}

Function.prototype.test = function() {
	return Boolean(this.apply(null, arguments));
}

Object.prototype.keys = function() {
	var result = [];
	for (var key in this)
		result.push(key);
	return result;
}

/*
Object.prototype.inverted = function() {
	var result = {};
	for (var key in this) {
		var value = this[key];
		if (typeof(value) == "function")
			continue;

		result[value] = key;
	}
	return result;
}
*/

Object.prototype.pushValue = function(key, value) {
	var currentValue = this[key];
	if (currentValue && currentValue["push"])
		currentValue.push(value);
	else
		this[key] = [value];
}

Object.prototype.test = function(other) {
	return this == other;
}

function getObjectClass(obj) {
	if (obj != null && obj["constructor"])
		return obj.constructor.toString().match(/\w+/g)[1];
	else
		return typeof(obj);
}

String.prototype.startsWith = function(other) {
	return this.slice(0, other.length) == other;
}

String.prototype.endsWith = function(other) {
	return this.slice(this.length - other.length) == other;
}

String.prototype.contains = function(other) {
	return this.indexOf(other) != -1;
}

String.prototype.trim = function() {
	return this.replace(/^\s+/, "").replace(/\s+$/, "");
}

Math.toInterval = function(n, min, max) {
	return Math.max(Math.min(n, max), min);
}

function fadeElement(element, opacStart, opacEnd, millisec) {
	var speed = 50;
	var stepCount = Math.round(millisec / speed);
	var stepSize = Math.round(Math.abs(opacEnd - opacStart) / stepCount);

	var opac = opacStart;
	if (opacStart > opacEnd)
		stepSize = -stepSize;
	else if (opacStart == opacEnd)
		return;

	var timerHandle = setInterval(
		function() {
			setOpacity(element, opac);
			opac += stepSize;
			if (opac < 0 || opac > 100) {
				clearInterval(timerHandle);
				setOpacity(element, Math.toInterval(opac, 0, 100));
			}
		},
		speed
	);
}

function fadeIn(element, millisec) {
	fadeElement(element, 0, 100, millisec);
}

function fadeOut(element, millisec) {
	fadeElement(element, 100, 0, millisec);
}

function setOpacity(element, opacity) {
	if (opacity == 0)
		hideElement(element);
	else {
		var style = element.style; 
		style.opacity = (opacity / 100); 
		style.MozOpacity = (opacity / 100); 
		style.KhtmlOpacity = (opacity / 100); 
		style.filter = "alpha(opacity=" + opacity + ")";
		showElement(element);
	}
}
//-**/

function gipGetSelectCandidate() {
	return getElementsByAttribute("id", /_SelectCandidate$/, "SELECT")[0];
}

function gipGetSelectResult() {
	return getElementsByAttribute("id", /_SelectResult$/, "SELECT")[0];
}

function gipGetMaster() {
	var select = gipGetSelectCandidate();
	if (!select)
		return null;
		
	var name = select.id.replace(/_SelectCandidate$/, "_MultiLookupPicker_m");
	return window[name];
}

function gipSelectAll(select) {
	var options = $A(select.options);
	options.forEach(
		function(option) {
			option.selected = true;
		}
	);
}

function gipSelectOnly(select, values) {
	var options = $A(select.options);
	options.forEach(
		function(option) {
			option.selected = values.contains(option.text);
		}
	);
}

function gipClearSelected() {
	gipSelectAll(gipGetSelectResult());
	GipRemoveSelectedItems(gipGetMaster());
}

function gipGetSelected() {
	var options = $A(gipGetSelectResult().options);
	return options.map(toAttribute("text"));
}

function gipSetSelected(values) {
	gipClearSelected();
	gipSelectOnly(gipGetSelectCandidate(), values);
	GipAddSelectedItems(gipGetMaster());
}

function getFormControlTD(title) {
	var labels = getElementsByClass("ms-formlabel", document, "TD");
	if (labels) {
		var controlLabel = $A(labels).first(function(label) { return $T(label).trim().startsWith(title) });
		if (controlLabel)
			return getNextSibling(controlLabel, byTagName("TD"));
	}
	return null;
}

function getFormControlElement(title) {
	var td = getFormControlTD(title);
	if (!td)
		return null;
	
	var inputs = getChildrenElements(td, byTagName("INPUT"), true);
	if (inputs.length > 0)
		return inputs[0];
	
	var selects = getChildrenElements(td, byTagName("SELECT"), true);
	if (selects.length > 0)
		return selects[0];
	
	return null;
}

function setSelectedByText(select, text) {
	var i = $A(select.options).map(toAttribute("text")).indexOf(text);
	if (i != -1)
		select.selectedIndex = i;
}

function setSelectedByValue(select, value) {
	var i = $A(select.options).map(toAttribute("value")).indexOf(value);
	if (i != -1)
		select.selectedIndex = i;
}

function setFormControlValue(title, value) {
	var element = getFormControlElement(title);
	if (!element)
		return;
		
	if (element.tagName == "INPUT")
		element.value = value;
	else if (element.tagName == "SELECT")
		setSelectedByText(element, value);
}

function getFormControlValue(title) {
	var element = getFormControlElement(title);
	if (!element)
		return;
		
	if (element.tagName == "INPUT")
		return element.value;
	else if (element.tagName == "SELECT")
		return element.options[element.selectedIndex].text;
}

function hideChildren(element) {
	Array.prototype.forEach.call(
		element.childNodes,
		function(child) {
			hideElement(child);
		}
	);
}

function replaceFormControl(title, newElement) {
	var controlTD = (typeof(title) == "string") ? getFormControlTD(title) : title;
	if (controlTD) {
		hideChildren(controlTD);
		controlTD.appendChild(newElement);
	}
}

function googleSearch(expr, sitesearch) {
  if (sitesearch)
    expr += " site:" + window.location.host;

  var parameters = encodeParameters(["q"], [expr]);
  var url = "http://www.google.com/search?" + parameters;
  STSNavigate(url);
}

function redirectEnter(event, func) {
  var key = event.keyCode ? event.keyCode : event.which;
  if (key == 13) {
    func();
    return false;
  }
  return true;
}

Math.randomInt = function(start, end) {
	return start + Math.floor(Math.random() * (end - start));
}

function prepara_logon_ajax(opcoes) {
	var gerenciador = new LogonAjax(opcoes);

	var tenta_logon = function(e) {
		redirectEnter(
			e,
			function() {
				gerenciador.logon()
			}
		);
	};
	addEvent($(opcoes.input_usuario), "keydown", tenta_logon);
	addEvent($(opcoes.input_senha), "keydown", tenta_logon);
	if (opcoes.botao_entrar) {
		addEvent(
			$(opcoes.botao_entrar),
			"click",
			function() {
				gerenciador.logon()
			}
		);
	}

	if (opcoes.botao_sair) {
		addEvent(
			$(opcoes.botao_sair),
			"click",
			function() {
				gerenciador.logoff()
			}
		);
	}
}

/**
 * input_usuario*
 * input_senha*
 * painel_logon
 * aguarde
 * botao_entrar
 * botao_sair
 * painel_usuario_logado
 * usuario_logado
 */
function LogonAjax(opcoes) {
	this.opcoes = opcoes;
	
	var _this = this;
	registerCallback(
		"logon_entrou",
		function() {
			hideElement($(_this.opcoes.aguarde));
			_this.mostra_logado();
		}
	);
	registerCallback(
		"logon_saiu",
		function() {
			_this.mostra_deslogado();
		}
	);
	registerCallback(
		"logon_falhou",
		function() {
			hideElement($(_this.opcoes.aguarde));
			_this.erro();
		}
	);
	
	if (Logon.usuario_logado())
		this.mostra_logado();
	else
		this.mostra_deslogado();
}

LogonAjax.prototype.logon = function() {
	this.mostra_logando();
	var usuario = $(this.opcoes.input_usuario).value;
	var senha = $(this.opcoes.input_senha).value;
	$(this.opcoes.input_senha).value = "";

	var _this = this;
	Logon.logon(
		usuario,
		senha
	);
}

LogonAjax.prototype.logoff = function() {
	Logon.logoff();
}

LogonAjax.prototype.sucesso = function() {
	this.mostra_logado();
}

LogonAjax.prototype.erro = function() {
	showElement($(this.opcoes.painel_logon));
	var mensagem;
	if (GetCookie("idioma") == "es")
		mensagem = "No fue posible efectuar el logon.\n\nVerifique el e-mail y la seña y trate de nuevo.";
	else
		mensagem = "Não foi possível efetuar o logon.\n\nVerifique o e-mail e a senha e tente novamente."
	alert(mensagem);
}

LogonAjax.prototype.mostra_logado = function() {
	this.atualiza_usuario();
	hideElement($(this.opcoes.painel_logon));
	hideElement($(this.opcoes.botao_entrar));
	showElement($(this.opcoes.botao_sair));
	showElement($(this.opcoes.painel_usuario_logado));
}

LogonAjax.prototype.mostra_deslogado = function() {
	showElement($(this.opcoes.painel_logon));
	showElement($(this.opcoes.botao_entrar));
	hideElement($(this.opcoes.botao_sair));
	hideElement($(this.opcoes.painel_usuario_logado));
}

LogonAjax.prototype.mostra_logando = function() {
	hideElement($(this.opcoes.painel_logon));
	showElement($(this.opcoes.aguarde));
}

LogonAjax.prototype.atualiza_usuario = function() {
	if (this.opcoes.usuario_logado)
		$(this.opcoes.usuario_logado).innerHTML = /*traduz_texto("Usuário: ") +*/ Logon.nome_usuario();
}

Logon = {};

/*
Logon.logon = function(usuario, senha, func_resposta) {
	var request = new IframeRequest("http://argus.iica.ac.cr:19555/scripts/logon.aspx", ["usuario", "senha"]);
	request.send(
		[usuario, senha],
		function(doc) {
			var resultado = $T(_$(doc, "resultado")) == "sucesso";
			if (resultado) {
				SetCookie("usuario", usuario, "");
				SetCookie("id_usuario", $T(_$(doc, "id_usuario")), "");
				SetCookie("nome_usuario", $T(_$(doc, "nome_usuario")), "");

				dispatchCallbacks("logon_entrou");
			}
			if (func_resposta)
				func_resposta(resultado);
		}
	);
}

*/

Logon.logon = function(usuario, senha) {
	loadScript(appendParameters(["usuario", "senha"], [usuario, senha], "http://argus.iica.ac.cr:19555/scripts/logon_js.aspx"));
}

Logon.terminou = function(usuario, id_usuario, nome_usuario) {
	SetCookie("usuario", usuario, "/");
	SetCookie("id_usuario", id_usuario, "/");
	SetCookie("nome_usuario", nome_usuario, "/");
	dispatchCallbacks("logon_entrou");
}

Logon.logoff = function() {
	var usuario = Logon.usuario_logado();
	if (usuario) {
		SetCookie("usuario", "", "/");
		dispatchCallbacks("logon_saiu");
	}
}

Logon.usuario_logado = function() {
	return GetCookie("usuario");
}

Logon.usuario_sharepoint = function() {
	var texto_usuario = $T(getChildElement(document, byId(/_Menu_t$/)));
	if (texto_usuario && texto_usuario.contains(", "))
		return texto_usuario.split(", ")[1].trim();
	else
		return null;
}

Logon.id_usuario = function() {
	return GetCookie("id_usuario");
}

Logon.nome_usuario = function() {
	return GetCookie("nome_usuario");
}

function loog(msg) {
	if (Logon.usuario_sharepoint() == "ARGUS\\laurindo.rodrigues")
		alert(msg);
}

function expandir(objeto) {
	if (document.all[objeto].style.display == "none")
		document.all[objeto].style.display = ""
	else
		document.all[objeto].style.display = "none"
}

function extractData(collection) {
	var data = [];
	var fieldTitles;
	if (collection && collection["childNodes"]) {
		Array.prototype.forEach.call(
			collection.childNodes,
			function(item) {
				var itemData = extractItemData(item);
				if (itemData) {
					fieldTitles = itemData.fieldTitles;
					itemData.fieldTitles = undefined;
					data.push(itemData);
				}
			}
		);
	}
	data.fieldTitles = fieldTitles;
	return data;
}

function decodeHTML(encoded) {
	return encoded.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
}

function extractItemData(item) {
	if (!item || !item["childNodes"])
		return null;

	var data = {};
	var fieldTitles = {};
	Array.prototype.forEach.call(
		item.childNodes,
		function(field) {
			var name = field.className;
			if (name) {
				data[name] = decodeHTML(field.innerHTML);
				fieldTitles[name] = field.title;
			}
		}
	);
	data.fieldTitles = fieldTitles;
	return data;
}

function getTitleFromData(itemData, fields, fieldTitles) {
	fields = fields ? fields : itemData.keys();
	fields = fields.filter(function(field) { return Boolean(itemData[field]) });
	return fields.map(
		function(field) {
			var value = itemData[field];
			
			var label;
			if (fieldTitles && fieldTitles[field])
				label = fieldTitles[field] + ": ";
			else
				label = "";
				
			return label + value;
		}
	).join("\n");
}

function setTitleFromData(element, itemData, fields, fieldTitles) {
	element.title = getTitleFromData(itemData, fields, fieldTitles);
}

function appendTitleFromData(element, itemData, fields, fieldTitles) {
	var title = element.title ? (element.title + "\n\n") : "";
	element.title = title + getTitleFromData(itemData, fields, fieldTitles);
}

/*
// Primary colors: count = 1
// Web safe colors: count = 5
function randomColorFragment(count) {
	var delta = Math.floor(255 / count);
	return (Math.randomInt(0, count + 1) * delta).toString(16).padLeft(2, "0");
}

function randomPrimaryColor() {
	return "#" + randomColorFragment(1) + randomColorFragment(1) + randomColorFragment(1);
}

function borderAround(element) {
	var color = randomPrimaryColor();
	element.style.border = "2px " + color + " dotted";
}

function disableWithOverlay(element) {
//alert('will disable ' + element.tagName + '\n' + element.innerHTML);
	var overlay = document.createElement("DIV");
	element.parentNode.appendChild(overlay); //--> correto
//	element.appendChild(overlay);
	overlay.style.position = "absolute"; //--> correto
//	overlay.style.top = absoluteTop(element) + "px";
	overlay.style.top = "0px";
	overlay.style.left = absoluteLeft(element) + "px";
	overlay.style.width = getFullWidth(element) + "px";
	overlay.style.height = getFullHeight(element) + "px";
	overlay.style.background = "#ccc";
	overlay.style.color = "#ccc";
	overlay.innerHTML = ".";
//alert([overlay.style.top, overlay.style.left, overlay.style.width, overlay.style.height]);
//	element._overlay = overlay;

	borderAround(element.parentNode);
	borderAround(element);
	borderAround(overlay);
}
*/

String.prototype.repeat = function(count) {
	return new Array(count + 1).join(this);
}

String.prototype.padLeft = function(size, padding) {
	padding = padding ? padding : " ";
	var paddingCount = Math.min(Math.max(size - this.length, 0), size);
	return padding.repeat(paddingCount) + this;
}

String.prototype.padRight = function(size, padding) {
	padding = padding ? padding : " ";
	var paddingCount = Math.min(Math.max(size - this.length, 0), size);
	return this + padding.repeat(paddingCount);
}

function callOnReady() {
	var done = false;
	var dispatchOnReady = function () {
		if (done) return;
		done = true;
		dispatchCallbacks("onready");
	};
  
	if (document.addEventListener)
		document.addEventListener("DOMContentLoaded", dispatchOnReady, false);

	/*@cc_on @*/
	/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
	document.getElementById("__ie_onload").onreadystatechange = function() {
		if (this.readyState == "complete")
			dispatchOnReady();
	};
	/*@end @*/

	if (/WebKit/i.test(navigator.userAgent)) { 
		var timer = setInterval(
			function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(timer);
					dispatchOnReady();
				}
			},
			10
		);
	}

	addEvent(window, "load", dispatchOnReady);
}
callOnReady();

/*
// -> Element.show?
function mostra_elemento(nome) {
  var elemento = $(nome);
  elemento.style.display = "block";
}

// -> Element.hide?
function esconde_elemento(nome) {
  var elemento = $(nome);
  elemento.style.display = "none";
}

// -> hideAll? todos.each(function(x) {x.hide()})
function esconde_tudo(todos) {
  for (var i = 0; i < todos.length; i++)
    esconde_elemento(todos[i]);
}

// -> showOnly? todos.each(function(x) {if (x.test(nome) x.show() else x.hide()})
function mostra_apenas(nome, todos) {
  for (var i = 0; i < todos.length; i++) {
    if (todos[i] == nome)
      mostra_elemento(nome);
    else
      esconde_elemento(todos[i]);
  }
}
*/

/*
function getFormControlTD(title) {
	var titleNOBR = Array.prototype.first.call(
		document.getElementsByTagName("NOBR"),
		function(element) {
			return $T(element).startsWith(title);
		}
	);
	var titleHR = titleNOBR.parentNode;
	var titleTD = titleHR.parentNode;
	return titleTD.nextSibling;
}
*/

/*
function lista_webparts(obj) {
    var divs = $A(obj.getElementsByTagName('DIV'));
    var webparts = divs.filterValues('id', /^WebPart/);
    return webparts;
}
*/

/*
function tenta_logon(usuario, senha, func_resposta) {
	var request = new IframeRequest("/scripts/logon.aspx", ["usuario", "senha"]);
	request.send(
		[usuario, senha],
		function(doc) {
			var resultado = $T(_$(doc, "resultado")) == "sucesso";
			if (resultado)
				SetCookie("usuario", usuario, "");
			func_resposta(resultado);
		}
	);
}
*/

/* --> getModuleOption
function obtem_opcao(nome, valor_default) {
	if (window["exige_usuario"] && exige_usuario["opcoes"]) {
		var opcao = exige_usuario.opcoes[nome];
		return opcao == undefined ? valor_default : opcao;
	}
}
*/