function closeWidget(id)
{
    $('#' + id).fadeOut().hide();
}

function tgWidget(id, byId)
{
    if (byId) {
        var o = $('#' + id);
    } else {
        var o = $('#' + id + '> .mid');
    }
    if(o.css('display') != 'none') {
        o.fadeOut();
    } else {
        o.fadeIn();
    }
}

function confWidget(id)
{
    alert('Este widget não tem configuração disponível no momento');
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

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 montre(id) 
{
    var d = document.getElementById(id);
    for (var i = 1; i<=10; i++) {
        if (document.getElementById('smenu'+i)) {
            document.getElementById('smenu'+i).style.display = 'none';
        }
    }
    if (d) { 
        setCookie('menu', id);
        d.style.display='block';
    }
}


/**
* Função relacionada ao mascaramento de campos
*/
function cleanMask(val)
{
    var strCheck = "'[](){}<>=+-*/_|\~`!?@#$%^&:;,.";
    var aux="";
    var i;

    for(i=0; i<val.length; i++) {
        if(strCheck.indexOf(val.charAt(i))==-1) {
            aux+=val.charAt(i);
        }
    }
    return aux;
}



/**
* Função relacionada ao mascaramento de campos
*/
function maskCurrency(val, milSep, decSep)
{
    var aux="";
    var aux2="";

    var i,j;

    len = val.length;
    if (len == 0) {
        aux = '';
    } else if (len == 1) {
        aux = '0'+ decSep + '0' + val;
    } else if (len == 2) {
        aux = '0'+ decSep + val;
    } else if (len > 2) {
        aux2 = '';

        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += val.charAt(i);
            j++;
        }
        aux = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--) {
            aux += aux2.charAt(i);
        }
        aux += decSep + val.substr(len - 2, len);
    }
    return aux;
}



/**
* Função relacionada ao mascaramento de campos
*/
function mask(_mask, val)
{
    var i, mki;
    var aux="";

    for(i=mki=0; i<val.length; i++, mki++) {
        if(_mask.charAt(mki)=='' || _mask.charAt(mki)=='#' || _mask.charAt(i)==val.charAt(i)) {
            aux+=val.charAt(i);
        } else {
            aux+=_mask.charAt(mki)+val.charAt(i);
            mki++;
        }
    }
    return aux;
}



/**
* Função relacionada ao mascaramento de campos
*/
function maskEvent(field, _mask, event)
{
    var key ='';
    var aux='';
    var len=0;
    var i=0;
    var strCheck = '0123456789';
    var rcode = (window.Event) ? event.which : event.keyCode;

    if(rcode == 13 || rcode == 0 || field.value.length == _mask.length  || rcode == 8) {
        //Enter
        key=String.fromCharCode(rcode);

        if(rcode!=13 && rcode!=0 && rcode != 8) {
            return false;
        }

        return true;
    }

    //Get key value from key code
    key=String.fromCharCode(rcode);

    if( strCheck.indexOf(key) == -1 ) {
        //Not a valid key
        return false;
    }

    aux=field.value+key;
    //window.alert(aux);
    aux=mask(_mask,aux);
    //window.alert(aux);
    field.value=aux;
    return false;
}



/**
* Função relacionada ao mascaramento de campos
*/
function currencyFormat(fld, milSep, decSep, e)
{
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;

    if (whichCode == 13 || whichCode == 0 || whichCode == 8) {        //Enter ou TAB
        return true;
    }
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) {
        return false;  // Not a valid key
    }
    len = fld.value.length;
    for(i = 0; i < len; i++) {
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) {
            break;
        }
    }
    aux = '';
    for(; i < len; i++) {
        if (strCheck.indexOf(fld.value.charAt(i))!=-1) {
            aux += fld.value.charAt(i);
        }
    }
    aux += key;

    len = aux.length;
    if (len == 0) {
        fld.value = '';
    } else if (len == 1) {
        fld.value = '0'+ decSep + '0' + aux;
    } else if (len == 2) {
        fld.value = '0'+ decSep + aux;
    } else if (len > 2) {
        aux2 = '';

        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--) {
            fld.value += aux2.charAt(i);
        }
        fld.value += decSep + aux.substr(len - 2, len);
    }
    return false;
}


function sprintf()
{
	if (!arguments || arguments.length < 1 || !RegExp)
	{
		return;
	}
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str))
	{
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];
		
		//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
				alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
			       if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			  else if (pPad) pad = pPad;
			var justifyRight = true;
			       if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
			       if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
			       if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			var subst = param;
			       if (pType == 'b') subst = parseInt(param).toString(2);
			  else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			  else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			  else if (pType == 'u') subst = Math.abs(param);
			  else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
			  else if (pType == 'o') subst = parseInt(param).toString(8);
			  else if (pType == 's') subst = param;
			  else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			  else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
	return str;
}

function go( url, controller ) {

    div = document.getElementById('_content:'+controller);
    ajax = new Ajax( );
    ajax.makeRequest( url, function( ) {
            div.innerHTML = ajax.getResponseText( );
    });
    


}

function showPage( url ) {

    page = document.createElement('div');
    page.id = '_divPage';
    
    ajax = new Ajax( );
    ajax.makeRequest( url, function( ) {
        page.innerHTML = ajax.getResponseText( );
    });
    
    document.body.appendChild( page );
    

}

function showController( controller, action ) {

    ctl = document.createElement('div');
    ctl.className = 'divCtl';
//    ctl.style.left = Math.random()*100;
    
    url = '?_layout=ajax&_ctl='+controller+'&_act='+action;
//        url = '?_ctl=cliente&_act=insert';
    ajax = new Ajax( );
    ajax.makeRequest( url, function( ) {
        ctl.innerHTML = ajax.getResponseText( );
    });
    
    document.body.appendChild( ctl );


}

function doFormAction( action, controller ) {
    if (action == 'delete') {
        if(!confirm("Tem certeza de que deseja remover ?")) {
            return false;
        }
    }
    document.getElementById('_action').value = action;
    document.forms["_controllerForm:"+controller].submit( );

}

function doAjaxSubmit( url, controller, action ) {

    form = document.forms['_controllerForm:'+controller];
    divId = '_content:'+controller;

    

    document.getElementById('_action').value = action;

    aSubmit = new ajaxSubmit( );
    aSubmit.makePostRequest( url, form, divId, action );

}


function buscaProdutoLoja()
{
    var p = $('#produto').val();
    window.location = '?_ctl=loja/Secao&secao=busca&q=' + p;
    return false;
}
function buscaProdutoLojaCM()
{
    var p = $('#produto').val();
    window.location = '?_ctl=lojacm/Secao&secao=busca&q=' + p;
    return false;
}


function loginShow(){
	var mask = $$('.cortina');
    $$('#media_box').setStyle('display', 'none');
	var btn_escritorio = $$('.lnk_escritorio');
	var btn_cancelar = $$('.btn_cancelar');

		$$('.div_login_escritorio').setStyle('display','block');
		mask.setOpacity(0.4);
		mask.setStyles({
			display : 'block',
			position : 'absolute',
			height : getPageSize().pageHeight
		});
    return false;
}

function loginHide(){
	var mask = $$('.cortina');
    $$('#media_box').setStyle('display', 'block');
	var btn_escritorio = $$('.lnk_escritorio');
	var btn_cancelar = $$('.btn_cancelar');

		$$('.div_login_escritorio').setStyle('display','none');
		mask.setOpacity(0.4);
		mask.setStyles({
			display : 'none',
			position : 'absolute',
			height : getPageSize().pageHeight
		});
    return false;
}

