/*
#######################################################################################
#Script com funções necessárias para execução das páginas em geral
#
#Desenvolvido pela Head Trust
#Criado em: 20/08/2008
#Modificado em: 24/08/2008 - 27/01/2009 - 09/07/2009
#######################################################################################
*/

//Declarando as variaveis
var $_GET = new Array();

//Chamando a função que executará o processo de inicialização do sistema
init();

function init(){
	loadUrlVars();
}

//Direciona para a página especificada
function source(source){
	window.location.href = source;
}

//Aliase para document.getElementById();
function $(idName){
	return document.getElementById(idName);
}

//Gera uma caixa de alerta de confirmação e segue o link
function confirmLocation(text,url){
	if(confirm(text)){
		source(url);
	}
}

//Variavel do ID
var counter = 0;
//Copia o HTML apartir de um ID
function copyField(copied, destiny){
	var local = $(destiny);
	var id = "AutoGerate$" + counter;
	var div = document.createElement('div');
	div.setAttribute("id", id);
	var field = $(copied).innerHTML;
	field += " <input type=\"button\" onclick=\"javascript:copyField('" + copied + "','" + destiny + "')\" value=\"Adicionar mais um\" special=\"dinamicButtonAdd\" />";
	field += "<input type=\"button\" onclick=\"javascript:removeField('" + destiny + "','" + id + "')\" value=\"X\" special=\"dinamicButtonRemove\" />";
	div.innerHTML = field;
	local.appendChild(div);
	counter++;
}

//Remove um campo adiciona dinamicamente
function removeField(local, id){
	var div = $(local);
	var field = $(id);
	div.removeChild(field);
}

//Simula um click no ID especificado
function clicking(id){
	$(id).click();
}

//Gera o efeito de desaparecer o texto com OnFocus
function onFocus(obj, text){
	if(obj.value == text){
		obj.value = '';
		obj.hasFocus = true;
	}
}

//Gera o efeito de reaparecer o texto com OnBlur
function onBlur(obj, text){
	if(obj.value == ''){
		obj.value = text;
		obj.hasFocus = false;
	}
}

//Adiciona um elemento de verificação de foco nos campos
var objectFields = new Array();
var total = 1;
var actual = 1;
function hasFocus(){
	for(var i = 0, df = document.forms, len = df.length; i < len; i++){
		for(j = 0, els = df[i].elements; j < els.length; j++){
			if( /^input|select|textarea/.test( els[j].type )){
				els[j].hasFocus = false;
				els[j].onfocus = (els[j].onfocus == null) ? function(){this.hasFocus = true;} : els[j].onfocus;
				els[j].onblur = (els[j].onblur == null) ? function(){this.hasFocus = false;} : els[j].onblur;
				objectFields[total] = els[j];
				total++;
			}
		}
	}
}

//Pula para o próximo campo da página
function nextField(){
	actual = (++actual > total) ? 1 : actual
	objectFields[actual].focus();
}

//Pula para o campo anterior da página
function prevField(){
	actual = (--actual < 1) ? total : actual
	objectFields[actual].focus();
}

//Pega a largura da janela
function getWindowWidth(){
	if (document.all){
		if (!document.documentElement.clientWidth){//Internet Explorer
			return document.body.clientWidth;                                                
		} else {//Demais navegadores
			return document.documentElement.clientWidth; 
		}
	} else {//FireFox
		return window.innerWidth; 
	}
}

//Pega a altura da janela
function getWindowHeight(){
	if (document.all){
		if (!document.documentElement.clientHeight){//Internet Explorer
			return document.body.clientHeight;                                                
		} else {//Demais navegadores
			return document.documentElement.clientHeight; 
		}
	} else {//FireFox
		return window.innerHeight; 
	}
}

//Retorna um array com a altura e largura da janela
function getWindowSize(){
	return {width:getWindowWidth(), height:getWindowHeight()};
}

//Pega a posição de um elemento da tela
function getElementPosition(elId){
    var offsetTrail = $(elId);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

//Desce o menu ou sobe-o
function dropMenu(parentId, childId, type){
	var parentTop = getElementPosition(parentId).top;
	var parentLeft = getElementPosition(parentId).left;
	var childElement = document.getElementById(childId);

	if((childElement.style.display == 'none') || (childElement.style.display == '')){
		childElement.style.position = 'absolute';
		childElement.style.display = 'block';

		if(type > 0){
			childElement.style.top = parentTop;
			childElement.style.left = (parentLeft + 202);
		} else {
			retreatAllMenus(childId);
			childElement.style.top = (parentTop + 30);
			childElement.style.left = parentLeft;
		}
	} else {
		childElement.style.display = 'none';
	}
}

function retreatAllMenus(childId){
	var allDivs = document.getElementsByTagName('div');

	for(var i = 0; i < allDivs.length; i++){
		if((allDivs[i].id != childId) && (strpos(allDivs[i].id, 'htdroplistmenu') !== false)){
			allDivs[i].style.display = 'none';
		}
	}
}

/*
 * Funções referentes à parte pública do site.
 */
 
function switchImage(obj){
	$('clinic-switch-image-spot').style.background = "url('" + obj.src + "') no-repeat center";
}

/*
 * A função a seguir, vai gerar as variavel $_GET da mesma maneira que funciona no PHP
 */

function loadUrlVars(){
	var hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 
    for(var i = 0; i < hashes.length; i++){
    	hash = hashes[i].split('=');
    	$_GET[urldecode(hash[0])] = urldecode(hash[1]);
    }
}

/*
 * Funções relativas ao do PHP
 * Os nomes declarados são os mesmo.
 * E a funcionalidade também.
 * Funções extraidas do site (http://phpjs.org/)
 */
 
function number_format (number, decimals, dec_point, thousands_sep) {
	number = (number + '').replace(',', '').replace(' ', '');
	var n = !isFinite(+number) ? 0 : +number,
		prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
		s = '',
		toFixedFix = function (n, prec) {
			var k = Math.pow(10, prec);
			return '' + Math.round(n * k) / k;        };
	// Fix for IE parseFloat(0.55).toFixed(0) = 0;
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}
 
function strpos (haystack, needle, offset) {
	var i = (haystack + '').indexOf(needle, (offset || 0));
	return i === -1 ? false : i;
}

function nl2br (str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br />';
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function trim (str, charlist) {

	var whitespace, l = 0, i = 0;
	str += '';
 
	if (!charlist) {        // default list
		whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
	} else {
		// preg_quote custom list
		charlist += '';
		whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
	}
 
	l = str.length;
	for (i = 0; i < l; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	} 
	l = str.length;
	for (i = l - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
 
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function htmlentities (string, quote_style) {
	var hash_map = {},
		symbol = '',
		tmp_str = '',
		entity = '';
	tmp_str = string.toString();
 
	if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
		return false;
	}
	hash_map["'"] = '&#039;';
	for (symbol in hash_map) {
		entity = hash_map[symbol];
		tmp_str = tmp_str.split(symbol).join(entity);
	}
 
	return tmp_str;
}

function get_html_translation_table (table, quote_style) {
	
	var entities = {}, hash_map = {}, decimal = 0, symbol = '';
	var constMappingTable = {}, constMappingQuoteStyle = {};
	var useTable = {}, useQuoteStyle = {};
 
	// Translate arguments
	constMappingTable[0] = 'HTML_SPECIALCHARS';
	constMappingTable[1] = 'HTML_ENTITIES';
	constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
	constMappingQuoteStyle[2] = 'ENT_COMPAT';
	constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
	useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
	useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
	if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
		throw new Error("Table: " + useTable + ' not supported');
        // return false;
	}
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
		entities['160'] = '&nbsp;';
		entities['161'] = '&iexcl;';
		entities['162'] = '&cent;';
		entities['163'] = '&pound;';
		entities['164'] = '&curren;';
		entities['165'] = '&yen;';
		entities['166'] = '&brvbar;';
		entities['167'] = '&sect;';
		entities['168'] = '&uml;';
		entities['169'] = '&copy;';
		entities['170'] = '&ordf;';
		entities['171'] = '&laquo;';
		entities['172'] = '&not;';
		entities['173'] = '&shy;';
		entities['174'] = '&reg;';
		entities['175'] = '&macr;';
		entities['176'] = '&deg;';
		entities['177'] = '&plusmn;';
		entities['178'] = '&sup2;';
		entities['179'] = '&sup3;';
		entities['180'] = '&acute;';
		entities['181'] = '&micro;';
		entities['182'] = '&para;';
		entities['183'] = '&middot;';
		entities['184'] = '&cedil;';
		entities['185'] = '&sup1;';
		entities['186'] = '&ordm;';
		entities['187'] = '&raquo;';
		entities['188'] = '&frac14;';
		entities['189'] = '&frac12;';
		entities['190'] = '&frac34;';
		entities['191'] = '&iquest;';
		entities['192'] = '&Agrave;';
		entities['193'] = '&Aacute;';
		entities['194'] = '&Acirc;';
		entities['195'] = '&Atilde;'; 
		entities['196'] = '&Auml;';
		entities['197'] = '&Aring;';
		entities['198'] = '&AElig;';
		entities['199'] = '&Ccedil;';
		entities['200'] = '&Egrave;';
		entities['201'] = '&Eacute;';
		entities['202'] = '&Ecirc;';
		entities['203'] = '&Euml;';
		entities['204'] = '&Igrave;';
		entities['205'] = '&Iacute;';
		entities['206'] = '&Icirc;';
		entities['207'] = '&Iuml;';
		entities['208'] = '&ETH;';
		entities['209'] = '&Ntilde;';
		entities['210'] = '&Ograve;';
		entities['211'] = '&Oacute;';
		entities['212'] = '&Ocirc;';
		entities['213'] = '&Otilde;';
		entities['214'] = '&Ouml;';
		entities['215'] = '&times;';
		entities['216'] = '&Oslash;';
		entities['217'] = '&Ugrave;';
		entities['218'] = '&Uacute;';
		entities['219'] = '&Ucirc;';
		entities['220'] = '&Uuml;';
		entities['221'] = '&Yacute;';
		entities['222'] = '&THORN;';
		entities['223'] = '&szlig;';
		entities['224'] = '&agrave;';
		entities['225'] = '&aacute;';
		entities['226'] = '&acirc;';
		entities['227'] = '&atilde;';
		entities['228'] = '&auml;';
		entities['229'] = '&aring;';
		entities['230'] = '&aelig;';
		entities['231'] = '&ccedil;';
		entities['232'] = '&egrave;';
		entities['233'] = '&eacute;';
		entities['234'] = '&ecirc;';
		entities['235'] = '&euml;';
		entities['236'] = '&igrave;';
		entities['237'] = '&iacute;';
		entities['238'] = '&icirc;';
		entities['239'] = '&iuml;';
		entities['240'] = '&eth;';
		entities['241'] = '&ntilde;';
		entities['242'] = '&ograve;';
		entities['243'] = '&oacute;';
		entities['244'] = '&ocirc;';
		entities['245'] = '&otilde;';
		entities['246'] = '&ouml;';
		entities['247'] = '&divide;';
		entities['248'] = '&oslash;';
		entities['249'] = '&ugrave;';
		entities['250'] = '&uacute;';
		entities['251'] = '&ucirc;';
		entities['252'] = '&uuml;';
		entities['253'] = '&yacute;';
		entities['254'] = '&thorn;';
		entities['255'] = '&yuml;';
	}
 
	if (useQuoteStyle !== 'ENT_NOQUOTES') {
		entities['34'] = '&quot;';
	}
	
	if (useQuoteStyle === 'ENT_QUOTES') {
		entities['39'] = '&#39;';
	}
	entities['60'] = '&lt;';
	entities['62'] = '&gt;'; 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
		symbol = String.fromCharCode(decimal);
		hash_map[symbol] = entities[decimal];
    }
 
	return hash_map;
}

function html_entity_decode (string, quote_style) {
	var hash_map = {}, symbol = '', tmp_str = '', entity = '';
	tmp_str = string.toString();
 
	if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
		return false;
	} 

	// fix &amp; problem
	// http://phpjs.org/functions/get_html_translation_table:416#comment_97660
	delete(hash_map['&']);
	hash_map['&'] = '&amp;'; 
	for (symbol in hash_map) {
		entity = hash_map[symbol];
		tmp_str = tmp_str.split(entity).join(symbol);
	}
	tmp_str = tmp_str.split('&#039;').join("'");
 
	return tmp_str;
}

function urlencode (str) {
	str = (str + '').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+').replace(/~/g, '%7E');
}

function urldecode (str) {
	return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}

function empty (mixed_var) {
	var key;
	if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
    	 return true;
	}
 
    if (typeof mixed_var == 'object') {
    	for (key in mixed_var) {
    		return false;
		}
    	return true;
    } 
    return false;
}

function isset () {
	var a = arguments,
		l = a.length,
		i = 0,
		undef;
 
	if (l === 0) {
		throw new Error('Empty isset');
	}
 
	while (i !== l) {
		if (a[i] === undef || a[i] === null) {
			return false;
		}
		i++;
	}
	return true;
}

function str_replace (search, replace, subject, count) {
    j = 0,
    temp = '',
    repl = '',
    sl = 0,        fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    } 
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
            	this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !! argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
            	return true;
            }
        }
    } else {
        for (key in haystack) {
        	if (haystack[key] == needle) {
                return true;
            }
        }
    } 
    return false;
}
