
function confirmLink( theLink, theQuery ) {
    var isConfirmed = confirm( theQuery );
    if ( isConfirmed ) {
        theLink.href += '&isConfirmed=1';
    }
    return isConfirmed;
}

function cssClick( e, classBase ) {
    classOver = classBase + '_over';
    classClick = classBase + '_click';
    if ( e.className == classBase || e.className == classOver ) {
        e.className = classClick;
    } else {
        e.className = classBase;
    }
}

function cssOver( e, classBase ) {
    classOver = classBase + '_over';
    classClick = classBase + '_click';
    if ( e.className != classClick ) {
        e.className = classOver;
    }
}

function cssOut( e, classBase ) {
    classOver = classBase + '_over';
    classClick = classBase + '_click';
    if ( e.className != classClick ) {
        e.className = classBase;
    }
}

function selectAllCheckboxes( name, do_check ) {
    var el = document.getElementsByTagName( name );
    var el_cnt = ( typeof( el.length ) != 'undefined') ? el.length : 0;
    if ( el_cnt ) {
        for ( var i = 0; i < el_cnt; i++ ) {
            el[i].checked = do_check;
        }
    } else {
        el.checked = do_check;
    }
    return true;
}

function setCheckboxes( the_form, do_check ) {
    var el = document.getElementsByTagName( 'input' );
    var el_cnt = ( typeof( el.length ) != 'undefined') ? el.length : 0;
    if ( el_cnt ) {
        for ( var i = 0; i < el_cnt; i++ ) {
            el[i].checked = do_check;
        }
    } else {
        el.checked = do_check;
    }
    return true;
}

function invertCheckboxes( the_form ) {
    var el = document.forms[the_form].elements['node[]'];
    var el_cnt = (typeof(el.length) != 'undefined') ? el.length : 0;
    if ( el_cnt ) {
        for ( var i = 0; i < el_cnt; i++ ) el[i].checked = !el[i].checked;
    } else {
        el.checked = !el.checked;
    }
    return true;
}


/* Despliega de tabs, del buscador */
function show_tabs( currentTab ) {    
    if ( currentTab == undefined ) {
        currentTab = 0;
    }
    if ( array_data == undefined ) {
        array_data = new Array(0);
    }
    for ( i in array_data ) {
        tabEl = document.getElementById( 'tab_' + array_data[i] );
        if ( i != currentTab ) {
            if ( tabEl ) {
                tabEl.style.display = 'none';
            }
            document.getElementById( 'btn_' + array_data[i] ).className = 'inactive';
        } else {
            document.getElementById( 'defaultGroupValue' ).value = i;            
            if ( tabEl ) {
                tabEl.style.display = 'block';
            }
            document.getElementById( 'btn_' + array_data[i] ).className = 'selected';
        }
    }

}


/* Funciones para mostrar un calendario */
var calendarLinks = new Array();

function SACCalGetTime() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    now = null;
    var ampm = "";
    if ( hour >= 12 ) {
        hour -= 12;
        ampm = "PM";
    } else {
        ampm = "AM";
    }
    hour = (hour == 0) ? 12 : hour;
        
    if ( minute < 10 ) {
        minute = "0" + minute;
    }    
    return hour + ":" + minute + " " + ampm;
}

function SACCalLeapYear( year ) {
    if ( year % 4 == 0 ) {
        return true;
    } else {
        return false;
    }
}

function SACCalGetDays( month, year ) {
    var ar = new Array(12);
    ar[0] = 31; // Enero
    ar[1] = ( SACCalLeapYear( year ) ) ? 29 : 28; // Febrero
    ar[2] = 31; // Marzo
    ar[3] = 30; // Abril
    ar[4] = 31; // Mayo
    ar[5] = 30; // Junio
    ar[6] = 31; // Julio
    ar[7] = 31; // Augosto
    ar[8] = 30; // Septiembre
    ar[9] = 31; // Octubre
    ar[10] = 30; // Noviembre
    ar[11] = 31; // Diciembre
    return ar[month]
        }

function SACCalGetMonthName( month, lang ) {
    var ar = new Array(12);
    if ( lang == "en" ) {
        ar[0] = "January";
        ar[1] = "February";
        ar[2] = "March";
        ar[3] = "April";
        ar[4] = "May";
        ar[5] = "June";
        ar[6] = "July";
        ar[7] = "August";
        ar[8] = "September";
        ar[9] = "October";
        ar[10] = "November";
        ar[11] = "December";
    } else {
        ar[0] = "Enero";
        ar[1] = "Febrero";
        ar[2] = "Marzo";
        ar[3] = "Abril";
        ar[4] = "Mayo";
        ar[5] = "Junio";
        ar[6] = "Julio";
        ar[7] = "Agosto";
        ar[8] = "Septiembre";
        ar[9] = "Octubre";
        ar[10] = "Noviembre";
        ar[11] = "Diciembre";
    }
    
    return ar[month];
}

function SACCalGetDayOfWeek( day, lang ) {
    var weekDay = new Array(7);
    if ( lang == "en" ) {
        weekDay[0] = "Sun";
        weekDay[1] = "Mon";
        weekDay[2] = "Tue";
        weekDay[3] = "Wed";
        weekDay[4] = "Thu";
        weekDay[5] = "Fri";
        weekDay[6] = "Sat";
    } else {
        weekDay[0] = "Dom";
        weekDay[1] = "Lun";
        weekDay[2] = "Mar";
        weekDay[3] = "Mié";
        weekDay[4] = "Jue";
        weekDay[5] = "Vie";
        weekDay[6] = "Sáb";
    }
    return weekDay[day];
}

function SACCalDrawCal( lang, eId, year, month, day, nId ) {
    
        /* Encontrar el elemento donde generar el calendario */
    var el = document.getElementById( eId );    
    if ( !el ) {
        return;
    }
    while ( el.firstChild) {
        el.removeChild(el.firstChild);
    }

    if ( document.all ) {
        var classAttr = 'className';
    } else {
        var classAttr = 'class';
    }

    var now = new Date();
    var today = now.getDate();
    
    if ( year == 'undefined' ) {
        year = now.getYear();
    }
    if ( month == 'undefined' ) {
        month = now.getMonth();
    }
    if ( day == 'undefined' ) {    
        day = now.getDate();
    }
    
    var currentMonth = month == now.getMonth()
        && ( year == now.getYear() || year == now.getYear() + 1900 );

    if ( year < 1000 ) {
        year += 1900;
    }

    var pyear = year;
    var pmonth = month - 1;
    if ( pmonth < 0 ) {
        pyear = year - 1;
        pmonth = 11;
    }
    
    var nyear = year;
    var nmonth = month + 1;
    if ( nmonth == 12 ) {
        nyear = year + 1;
        nmonth = 0;
    }
    
    var monthName = SACCalGetMonthName( month, lang );
    var lastDate = SACCalGetDays( month, year, lang );
    var prevLastDate = SACCalGetDays( pmonth, pyear, lang );

    var firstDayInstance = new Date( year, month, 1 );
    var firstDay = firstDayInstance.getDay() + 1;
    firstDayInstance = null;

    var jumpToPrevMonth = "SACCalDrawCal( '" + lang + "', '" + eId + "', " + pyear + ", " + pmonth + ", 1, " + nId + " );";
    var jumpToNextMonth = "SACCalDrawCal( '" + lang + "', '" + eId + "', " + nyear + ", " + nmonth + ", 1, " + nId + " );";

    var jumpToPrevYear = "SACCalDrawCal( '" + lang + "', '" + eId + "', " + ( year - 1 ) + ", " + month + ", 1, " + nId + " );";
    var jumpToNextYear = "SACCalDrawCal( '" + lang + "', '" + eId + "', " + ( year + 1 ) + ", " + month + ", 1, " + nId + " );";

        /* Se arman los elementos del calendario */
    mainDiv = document.createElement( "div" );
    mainDiv.setAttribute( classAttr, "sac_calendar" );

    var table = document.createElement( "div" );
    table.setAttribute( classAttr, 'table' );

    var tr = document.createElement( "div" );
    tr.setAttribute( classAttr, 'title' );
    var th = document.createElement( "span" );
    th.setAttribute( classAttr, "prev_month" );
    var a = document.createElement( "a" );
    a.setAttribute( "onclick", jumpToPrevMonth );
    a.setAttribute( "href", 'javascript:' + jumpToPrevMonth );
//    a.appendChild( document.createTextNode( '< ' ) );
    a.appendChild( document.createTextNode( ' ' ) );
    th.appendChild( a );
    tr.appendChild( th );
    var th = document.createElement( "span" );
    th.setAttribute( classAttr, "title" );
    th.appendChild( document.createTextNode( monthName ) );
    tr.appendChild( th );
    var th = document.createElement( "span" );
    th.setAttribute( classAttr, "next_month" );
    var a = document.createElement( "a" );
    a.setAttribute( "onclick", jumpToNextMonth );
    a.setAttribute( "href", 'javascript:' + jumpToNextMonth );
    a.setAttribute( classAttr, 'next_month' );
//    a.appendChild( document.createTextNode( ' >' ) );
    a.appendChild( document.createTextNode( ' ' ) );
    th.appendChild( a );
    tr.appendChild( th );

    var th = document.createElement( "span" );
    th.setAttribute( classAttr, "prev_year" );
    var a = document.createElement( "a" );
    a.setAttribute( "onclick", jumpToPrevYear );
    a.setAttribute( "href", 'javascript:' + jumpToPrevYear );
//    a.appendChild( document.createTextNode( '< ' ) );
    a.appendChild( document.createTextNode( ' ' ) );
    th.appendChild( a );
    tr.appendChild( th );
    var th = document.createElement( "span" );
    th.setAttribute( classAttr, "title" );
    th.appendChild( document.createTextNode( year ) );
    tr.appendChild( th );
    var a = document.createElement( "a" );
    var th = document.createElement( "span" );
    th.setAttribute( classAttr, "next_year" );
    a.setAttribute( "onclick", jumpToNextYear );
    a.setAttribute( "href", 'javascript:' + jumpToNextYear );
    a.setAttribute( classAttr, 'next_year' );
//    a.appendChild( document.createTextNode( ' >' ) );
    a.appendChild( document.createTextNode( ' ' ) );
    th.appendChild( a );
    tr.appendChild( th );

    table.appendChild( tr );
    
    var tr = document.createElement( "div" );
    tr.setAttribute( classAttr, 'header' );
    for ( var dayNum = 0; dayNum < 7; ++dayNum ) {
        tr.appendChild( addText( "span", SACCalGetDayOfWeek( dayNum, lang ) ) );
    }
    table.appendChild( tr );
    var digit = 1;
    var curCell = 1;
    var nextMonthDay = 1;
    var extraCssClass;
    var typeOfEventsUsed = Array();
    var currElement = 0;
    for ( var row = 1;
          row <= Math.ceil( ( lastDate + firstDay - 1 ) / 7 );
          ++row) {
        var tr = document.createElement( "div" );
        tr.setAttribute( classAttr, 'row' );
        for ( var col = 1; col <= 7; ++col ) {
            if ( calendarLinks[nId]
                 && calendarLinks[nId][year]
                 && calendarLinks[nId][year][month + 1]
                 && calendarLinks[nId][year][month + 1][digit] ) {
                var anchor = document.createElement( "a" );
                var importText = calendarLinks[nId][year][month + 1][digit];
                var typeEvent = parseInt( importText.substring( 0, 4 ), 10 );
                var completeText = importText.substring( 5 );
                var comma = completeText.search( ',' );
                var url = completeText.substring( 0, comma );
                var title = completeText.substring( comma + 1 );
                anchor.setAttribute( "href", url
                                     + ( url.indexOf( '?' ) < 0 ? '?' : '&' )
                                     + 'dateCalendar=' + year + '-' + ( month + 1 ) + '-' + digit );
                extraCssClass = '';
                if ( typeEvent > 0
                     && calendar_events
                     && calendar_events[typeEvent] ) {
                    extraCssClass = ' ' + calendar_events[typeEvent];
                    found = false;
                    for ( ti = 0; ti < typeOfEventsUsed.length; ti++ ) {
                        if ( calendar_events[typeEvent]
                             == typeOfEventsUsed[ti] ) {
                            found = true;
                            break;
                        }
                    }
                    if ( !found ) {
                        typeOfEventsUsed[currElement++]
                            = calendar_events[typeEvent];
                    }
                }
                anchor.appendChild( document.createTextNode( digit ) );
                anchor.setAttribute( "title", title );
                td = document.createElement( 'span' );
                td.setAttribute( "title", title );
                if ( currentMonth && digit == today ) {
                    td.setAttribute( classAttr,
                                     'now activity' + extraCssClass );
                } else {
                    td.setAttribute( classAttr,
                                     'activity' + extraCssClass );
                }
                td.appendChild( anchor );
                textLink = td;
            } else {
                if ( currentMonth && digit == today ) {
                    textLink = addText( "span", digit, 'now' );
                } else {
                    textLink = addText( "span", digit );
                }
            }
            
            if ( digit > lastDate ) {
                tr.appendChild( addText( "span", nextMonthDay++, "next_month" ) );
                continue;
            }
            if ( curCell < firstDay ) {
                tr.appendChild( addText( "span", prevLastDate + col - 5, "prev_month" ) );  
                curCell++;
            } else {
                tr.appendChild( textLink );
                digit++;
            }
        }
        table.appendChild( tr );
    }
    mainDiv.appendChild( table );
    el.appendChild( mainDiv );

    var table = document.createElement( "div" );
    table.setAttribute( classAttr, 'table' );
    for ( i = 0; i < typeOfEventsUsed.length; i++ ) {
        var tr = document.createElement( "div" );
        tr.setAttribute( classAttr, 'row' );
        
        var td = document.createElement( "span" );
        td.setAttribute( classAttr, 'activity ' + typeOfEventsUsed[i] );
        var anchor = document.createElement( "a" );
        anchor.appendChild( document.createTextNode( ' ... ' ) );
        td.appendChild( anchor );
        tr.appendChild( td );
        
        var td = document.createElement( "b" );
        td.setAttribute( classAttr, '' );
        td.appendChild( document.createTextNode( typeOfEventsUsed[i] ) );
        tr.appendChild( td );

        table.appendChild( tr );
    }
    el.appendChild( table );
}

function addText( type, value, ownclass ) {
    var td = document.createElement( type );
    if ( document.all ) {
        var classAttr = 'className';
    } else {
        var classAttr = 'class';
    }
    if ( ownclass ) {
        td.setAttribute( classAttr, ownclass );
    }
    text = document.createTextNode( value );
    td.appendChild( text );
    return td;
}

function _setStyle( element, declaration ) {
    if ( declaration.charAt( declaration.length - 1 ) == ';' ) {
        declaration = declaration.slice( 0, -1 );
    }
    var k, v;
    var splitted = declaration.split( ';' );
    for ( var i = 0, len = splitted.length; i < len; i++ ) {
        k = rzCC( splitted[i].split( ':' )[0] );
        v = splitted[i].split( ':' )[1];
        eval( "element.style." + k + "='" + v + "'" );
    }
}

function rzCC(s){
    for( var exp=/-([a-z])/; 
         exp.test(s); 
         s=s.replace( exp, RegExp.$1.toUpperCase() ) );
    return s;
}
	
function setServerTime ( timeString ){
    sH = timeString.substring(0,2);
    sM = timeString.substring(3,5);
    sS = timeString.substring(6,8);
    now = new Date();
    cH = now.getHours(); 
    cM = now.getMinutes(); 
    cS = now.getSeconds(); 
    difH = sH - cH;
    difM = sM - cM;
    difS = sS - cS;
}

function Syncronize() {
    now = new Date();
    cH = now.getHours(); 
    cM = now.getMinutes(); 
    cS = now.getSeconds(); 
    sH = difH + cH;
    sM = difM + cM;
    sS = difS + cS;
    if ( sS > 59 ) {
        sS -= 60;
        sM = sM + 1;
    }
    if ( sM > 59 ) {
        sM -= 60;
        sH = sH + 1;
    }
    if ( sH > 23 ) {
        sH -= 24;
    }
    var finaltime = sH + ':'+((sM < 10)?"0"+sM:sM)+':'+((sS < 10)?"0"+sS:sS);
    if (document.all)
        hour.innerHTML=finaltime
            else if (document.getElementById)
                document.getElementById("hour").innerHTML=finaltime
                    else if (document.layers){
                        document.hourns.document.hourns2.document.write(finaltime)
                        document.hourns.document.hourns2.document.close()
                    }
    setTimeout('Syncronize()', 1000);
}

/* Select multiple */
function optionAdd(s_from, s_to, updateIn) {
    optionMove(s_from, s_to, updateIn, 1);
}
function optionDel(s_from, s_to, updateIn) {
    optionMove(s_from, s_to, updateIn, 2);
}
function optionAddAll(s_from, s_to, updateIn) {
    optionMoveAll(s_from, s_to, updateIn, 1);
}
function optionDelAll(s_from, s_to, updateIn) {
    optionMoveAll(s_from, s_to, updateIn, 2);
}

/* option = 1 (adicionar), option = 2 (borrar) */
function optionMove(s_from, s_to, updateIn, option) {
	var e_from = document.getElementById( s_from );
	var	e_to   = document.getElementById( s_to );		
	if (!e_from)
		return alert ( "Error: selectbox con nombre '" + s_from + "' no puede ser encontrado." );
	if (!e_to)
		return alert ( "Error: selectbox con nombre '" + e_to + "' no puede ser encontrado." );
	var n_moved = 0;
	for (var i = 0; i < e_from.options.length; i++) {
		if (e_from.options[i].selected) {
			e_to.options[e_to.options.length] = new Option(e_from.options[i].text, e_from.options[i].value);
			n_moved++;
		}
		else if (n_moved)
			e_from.options[i - n_moved] = new Option(e_from.options[i].text, e_from.options[i].value);
	}
	if (n_moved)
		e_from.options.length = e_from.options.length - n_moved;
	else
		alert( "No ha seleccionado ninguna opción" );

        /* Actualizar los datos en el elemento definido */
    if ( option == 1 ) {
        updateElementData( updateIn, s_to );
    } else {
        updateElementData( updateIn, s_from );
    }    
}

function optionMoveAll(s_from, s_to, updateIn, option ) {
	var e_from = document.getElementById( s_from );
	var	e_to   = document.getElementById( s_to );
	if (!e_from)
		return alert ( "Error: selectbox nombre '" + s_from + "' no puede ser encontrado." );
	if (!e_to)
		return alert ( "Error: selectbox nombre '" + s_from + "' no puede ser encontrado." );

    if ( e_from.options.length == 0 ) {
        return;
    }
    var j = 0;
    var lengthTo = e_to.options.length;
	for (var i = lengthTo ; i < e_from.options.length + lengthTo ; i++) {
        e_to.options[i] = new Option(e_from.options[j].text, e_from.options[j].value);
        j++;
    }
	e_from.options.length = 0;
    
        /* Actualizar los datos en el elemento definido */
    if ( option == 1 ) {
        updateElementData( updateIn, s_to );
    } else {
        updateElementData( updateIn, s_from );
    }    
}

function selectAll (s_select) {
	var e_select = document.getElementById( s_select );
	for (var i = 0; i < e_select.options.length; i++)
			e_select.options[i].selected = true;
}

function loadDataToTransferSelect( fieldId, srcSelectName, destSelectName ) {    
    var field = document.getElementById( fieldId );
	var e_from = document.getElementById( srcSelectName );
	var	e_to   = document.getElementById( destSelectName );
    var arrayData = field.value.split( ',' );
    var k, j, i, lenTo;
    for (i = 0 ; i < arrayData.length ; i++){
       k = 0;
       lenTo = e_to.options.length;
       for  (j = 0 ; j < e_from.options.length ; j++) {
           if ( arrayData[i] != e_from.options[j].value ) {
               e_from.options[k] = new Option(e_from.options[j].text,
                                              e_from.options[j].value);
               k++;
           } else {
               e_to.options[lenTo] = new Option(e_from.options[j].text,
                                                e_from.options[j].value);
               lenTo++;
           }
       }
       e_from.options.length = k;
    }
}
function updateElementData( fieldId, s_to ) {
    var field = document.getElementById( fieldId );
    var	e_to   = document.getElementById( s_to );
    field.value = '';
    for ( var i = 0 ; i < e_to.options.length ; i++) {
        if ( field.value != '' ) {
            field.value += ',';
        }
        field.value += e_to.options[i].value;
    }   
}

/*
 * Script para insertar el contenido de un combo en un template
 * extraído y adaptado de phpMyAdmin
 */
function insertValueFromCombo( comboBox, template, prefix ) {
    if(comboBox.options.length > 0) {
        var text = '';
        var NbSelect = 0;
        for(var i=0; i<comboBox.options.length; i++) {
            if (comboBox.options[i].selected){
                NbSelect++;
                if (NbSelect > 1)
                    text += ' ';
                text += '{'+ prefix + comboBox.options[i].value + '}';
            }
        }
        //Retrieve the template name
        eText = document.getElementById( template );
        insertValue( text, eText );
    }
}

function insertValue( text, template ) {
    //IE support
    if (document.selection) {
        template.focus();
        sel = document.selection.createRange();
        sel.text = text;
        template.insert.focus();
    }
    //MOZILLA/NETSCAPE support
    else if (template.selectionStart || template.selectionStart == '0') {
        var startPos = template.selectionStart;
        var endPos = template.selectionEnd;
        var chaineSql = template.value;

        template.value = chaineSql.substring(0, startPos) + text + chaineSql.substring(endPos, chaineSql.length);
    } else {
        template.value += text;
    }
}

function openwindow( url, width, height ) {
    window.open(
        url,
        'newWindow1',
        'width=' + width + ', height=' + height + ', top=0, left=0, toolbar=no, location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=1' );
}

    /* Abrir una imagen con el ancho y alto solicitado, el ancho máximo será 800px y el alto máximo 600px */
function verimagen( url, width, height ) {
    maxHeight = 600;
    maxWidth = 800;
    if ( height > maxHeight ) {
        height = maxHeight;
    }
    if ( width > maxWidth ) {
        width = maxWidth;
    }
    openwindow( url, width, height );
}

/* Ajax segment */
var xmlhttp;
var xmlhttpNodeId;

/* [url] contiene la dirección completa de donde se obtiene información (parcial)
 * [elementId] contiene el id del elemento html a actualizar */
function remoteProcedure( url, elementId ) {
    xmlhttp = GetXmlHttpObject();
    if ( xmlhttp==null ) {
        /* Die in silent mode */;
        return;
    }
    xmlhttpNodeId = elementId;
    xmlhttp.onreadystatechange = function() {
        if ( xmlhttp.readyState == 4 ) {
            document.getElementById( xmlhttpNodeId ).innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open( 'GET', url, true);
    xmlhttp.send( null );
    return false;
}

function GetXmlHttpObject() {
    if ( window.XMLHttpRequest ) { // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if ( window.ActiveXObject ) { // code for IE6, IE5
        return new ActiveXObject( "Microsoft.XMLHTTP" );
    }
    return null;
}

function display_form_group( groupId ) {    
    el = document.getElementById( groupId );
    elImg = document.getElementById( 'img_' + groupId );
    if ( el.style.display == 'none' ) {
        el.style.display = 'block';
        elImg.src = elImg.src.replace( 'row_hide.png', 'row_show.png' );
    } else {
        el.style.display = 'none';
        elImg.src = elImg.src.replace( 'row_show.png', 'row_hide.png' );
    }    
}

/* Utilizada en una pieza scroll */
scrollPosition = Array;
function sac_setScrollTo( id, scrollDelay, scrollStep, scrollHorizontal ) {
    e = document.getElementById( id );
    scrollPosition[id] = 0;
    if ( scrollDelay < 1 ) scrollDelay = 1;
    if ( scrollStep < 1 ) scrollStep = 1;
    setInterval( "sac_scroll('" + id + "', " + scrollStep + ", " + scrollHorizontal + ")", scrollDelay );
}

function sac_scroll( id, scrollStep, scrollHorizontal ) {
    e = document.getElementById( id );
    scrollPosition[id] += scrollStep;
    if ( scrollHorizontal == false ) {       
        e.style.top = -scrollPosition[id] + 'px';
        if ( scrollPosition[id] > e.clientHeight + scrollStep )
            scrollPosition[id] = -e.parentNode.clientHeight;
    } else {
        e.style.left = -scrollPosition[id] + 'px';
        if ( scrollPosition[id] > e.clientWidth + scrollStep )
            scrollPosition[id] = -e.parentNode.clientWidth;        
    }    
}

