// $Id: tools.js,v 2.26 2008/06/14 01:00:00 rbravo Exp $
var hname = location.hostname;
var path = location.pathname;
var target_url = hname + path;
function openwin( url ) {
    popupwin ( url, 600, 800, 0, 0 );
}
function popupwin ( url, width, height, left, top ) {
    var nue_vent = window.open (url, 'pop_win', config='height=' + height + ', width=' + width + ', toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no');

    if ( ! nue_vent.opener ) nue_vent.opener = self;
    nue_vent.moveTo (left, top);
}
/* 
 * checkall.js
 *    uso:
 *    <form name="myform" id="myform">
 *    <input type="hidden" name="cant_seleccionados">
 *    <input type="checkbox" name="checkall" class="checkall" onClick="checkAll(myform, 'nombre_campo');">
 *    <input type="checkbox" ... class="nombre_campo" onClick="aToggle(myform);">
 * setea la variable "cant_seleccionados" para poder mostrar en un alert su cantidad
*/
function checkAll(formId, cName) {
    if ( formId.checkall.checked ) {
        var checked_counter = 0;
        for (i=0,n=formId.elements.length;i<n;i++) {
            if (formId.elements[i].className.indexOf(cName) !=-1) {
                formId.elements[i].checked = true;
                checked_counter++;
            }
        }
        // formId.cant_seleccionados.value=0; // para que el cartel diga "todos los elementos"
        formId.cant_seleccionados.value = checked_counter;
    } else {
        for (i=0,n=formId.elements.length;i<n;i++)
            if (formId.elements[i].className.indexOf(cName) !=-1)
                formId.elements[i].checked = false;
    }
}
function aToggle(formId) {
    formId.checkall.checked = false;
    formId.cant_seleccionados.value = 0;
    for (i=0,n=formId.elements.length;i<n;i++)
        if ( formId.elements[i].checked )
                formId.cant_seleccionados.value++;
}
function trim(str) {
   return str.replace(/^\s*|\s*$/g,"");
}
// adds to input integer value delta (positive or negative) up to limit (to use with up/down arrows)
function add(field, delta, limit) {
    if ( delta == undefined || isNaN(delta) ) delta = 1;
    if ( field != undefined && field != '' ) {
        var input = document.getElementById(field);
        if ( input != undefined && ! isNaN(input.value) && input.value == parseInt(input.value, 10) ) {
            if ( limit == undefined || limit == ''
                || ( ! isNaN(limit) && delta > 1 && input.value < limit) || ( ! isNaN(limit) && delta < 1 && input.value > limit) )
            {
                delta = delta * 1;
                var input_val = input.value * 1;
                input.value = input_val + delta;
            }
        } else {
            input.value = 1;
        }
    }
    return;
}
function num_ar2us ( num ) {
    num = num + '';
    output = num.replace(/\,/g,'.');
    return output;
}
function num_us2ar ( num ) {
    num = num + '';
    output = num.replace(/\./g,',');
    return output;
}
function check_int(field, msg) {
    var value = field.value;
    var output = true;
    field.style.backgroundColor = 'white';
    if ( value != undefined && value != '' ) {
        if ( value != parseInt(value,10) ) {
            output = false;
            bad_field(field, msg);
        }
    }
    return output;
}
function check_num(field, msg) {
    var value = field.value;
    var output = true;
    field.style.backgroundColor = 'white';
    if ( value != undefined && value != '' ) {
        var num_regex = /^[+-]?\d+[,.]?\d*$/;
        if ( ! num_regex.test(value) ) {
            output = false;
            bad_field(field, msg);
        }
    }
    return output;
}
function is_valid(field, type, msg) {
    if ( type == 'alfa' ) var myregex = /^[a-zA-Z]+$/;
    if ( type == 'alfanum' ) var myregex = /^[\w]*$/;
    if ( type == 'alfanumspaces' ) var myregex = /^[\w\s]*$/;
    if ( type == 'alfanumunder' ) var myregex = /^[_\w]*$/;
    if ( type == 'alfanumunderhyphen' ) var myregex = /^[-_\w]*$/;
    if ( type == 'bool' ) var myregex = /^on$/; // checkbox's value is always on, the true value is 'checked' bool property
    if ( type == 'date' ) var myregex = /^\d\d\d\d-\d\d-\d\d$/;
    if ( type == 'datetime' ) var myregex = /^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/;
    if ( type == 'email' ) var myregex = /^[\w]([.]?([.\w-]+)*)?@([\w-]+\.)+[a-zA-Z]{2,6}$/;
    if ( type == 'file' ) var myregex = /^.+$/;
    if ( type == 'html' ) var myregex = /^.*$/;
    if ( type == 'id' ) var myregex = /^\d+$/;
    if ( type == 'imgfile' ) var myregex = /^.+\.(jpg|gif|png)$/i;
    if ( type == 'imgswffile' ) var myregex = /^.+\.(jpg|gif|swf|png)$/i;
    if ( type == 'integer' ) var myregex = /^[+-]?[\d]+$/;
    if ( type == 'jpgfile' ) var myregex = /^.+\.jpe?g$/i;
    if ( type == 'ln' ) var myregex = /^[a-z][a-z]$/;
    if ( type == 'mp3file' ) var myregex = /^.+\.mp3$/i;
    if ( type == 'natural' ) var myregex = /^[\d]+$/;
    if ( type == 'number' ) var myregex = /^[+-]?\d*\.?\d*$/; // numbers and optional - or + sign, no decimals
    if ( type == 'password' ) var myregex = /^[\S]{4,32}$/; // no spaces
    if ( type == 'phone' ) var myregex = /^\+?(\(?\d+\))?[\d\s-]{5,}(\s*(x|int)\s*\d+)?$/;
    if ( type == 'pixels' ) var myregex = /^[\d]+x[\d]+$/;
    if ( type == 'swffile' ) var myregex = /^.+\.swf$/i;
    if ( type == 'text' ) var myregex = /^.*$/m;
    if ( type == 'url_http' ) var myregex = /^.*$/;
    if ( type == 'wavfile' ) var myregex = /^.+\.wav$/i;
    var value = field.value;
    var output = false;
    if ( myregex != undefined && value != '' ) {
        if ( myregex.test(value) ) {
            output = true;
        }
    }
    field.style.backgroundColor = 'white';
    if ( ! output ) bad_field(field, msg);
    return output;
}
function bad_field(field, msg) {
    if ( ! (field && msg) ) return;
    field.style.backgroundColor = 'red';
    alert(msg);
    field.focus();
    return;
}
function money_format(number, type, decimals) { // type: ar, us; decimals: 0, 1, 2
    number = number + '';
    var output = '';
    if ( type == undefined ) type = 'ar';
    if ( decimals == undefined ) decimals = 2;
    if ( type == 'ar' ) {
        var separator = ',';
    } else if ( type == 'us' ) {
        var separator = '.';
    } else {
        var separator = ',';
    }
    var parts = new Array(2);
    if ( number.indexOf(',' ) != -1 ) {
        parts = number.split(',');
    } else if ( number.indexOf('.' ) != -1 ) {
        parts = number.split('.');
    } else {
        parts[0] = number;
        parts[1] = '00';
    }
    parts[1] = parts[1].substr(0,decimals);
    while ( parts[1].length < decimals ) {
        parts[1] += '0';
    }
    output = parts.join(separator);
    return output;
}
function strip_units(cadena) { // strips out px/pt/cm/% units
    if ( cadena == '' || cadena == undefined ) return;
    var ultimos_uno = cadena.substring(cadena.length-1,cadena.length);
    var ultimos_dos = cadena.substring(cadena.length-2,cadena.length);
    var output = cadena;
    if ( ultimos_dos == 'px' || ultimos_dos == 'pt' || ultimos_dos == 'cm' ) {
        output = cadena.substring(0,cadena.length-2);
    } else if ( ultimos_uno == '%' ) {
        output = cadena.substring(0,cadena.length-1);
    }
    output = output * 1;
    return output;
}
function enadisa_inputs(action) { // enable/disable input changes (in order to block form while Ajax is working)
    var new_disa = ( action == undefined || action == 'ena' ) ? false : true;
    var new_cursor = new_disa ? 'wait' : 'default';
    var imgs_list = document.getElementsByTagName('img');
    document.body.style.cursor = new_cursor;
    for( i=0; i<imgs_list.length; i++) {
        var my_img = imgs_list[i];
        if ( my_img.useMap != undefined && my_img.useMap != '' ) {
            my_img.disabled = new_disa;
        }
    }
    var inputs_list = document.getElementsByTagName('input');
    for( i=0; i<inputs_list.length;i++) {
        var my_input = inputs_list[i];
        my_input.disabled = new_disa;
    }
    var select_list = document.getElementsByTagName('select');
    for( i=0; i<select_list.length;i++) {
        var my_select = select_list[i];
        my_select.disabled = new_disa;
    }
}
function findPosition( oElement ) {
    if ( typeof( oElement.offsetParent ) != 'undefined' ) {
        for ( var posX = oElement.scrollLeft, posY = oElement.scrollTop; oElement; oElement = oElement.offsetParent ) {
            posX += oElement.offsetLeft - oElement.scrollLeft;
            posY += oElement.offsetTop - oElement.scrollTop;
        }
        return [ posX, posY ];
    } else {
        return [ oElement.x, oElement.y ];
    }
}
function toggle_display(button, panel_id, deltaX, deltaY) { // necesita que el boton tenga la propiedad style:height definida
    if ( button == undefined || panel_id == undefined ) return;
    if ( deltaX == undefined || isNaN(deltaX) ) deltaX = 0;
    if ( deltaY == undefined || isNaN(deltaY) ) deltaY = 0;
    var panel = document.getElementById(panel_id);
    if ( panel.style.display == 'none' ) {
        var button_pos = findPosition(button);
        var button_height = strip_units(button.style.height);
        var panel_left = button_pos[0] + deltaX;
        panel.style.left = panel_left + 'px';
        var panel_top = button_pos[1] + button_height + deltaY;
        panel.style.top = panel_top + 'px';
        panel.style.display = 'inline';
    } else {
        panel.style.display = 'none';
    }
}
function check_thisonly (form_name, inputid_prefix, item_no) {
    if ( form_name ==  undefined || document.forms[form_name] == undefined || item_no == undefined ) return;
    var miform = document.forms[form_name];
    var pref_len = inputid_prefix.length;
    for ( i=1; i<miform.elements.length; i++ ) {
        var mielem = miform.elements[i];
        var my_id = mielem.id;
        if ( my_id.substr(0, pref_len) == inputid_prefix ) {
            if ( mielem.type == 'checkbox' ) {
                mielem.checked = ( mielem.id == inputid_prefix + item_no ) ? true : false;
            } else if ( mielem.type == 'hidden' ) {
                mielem.value = ( mielem.id == inputid_prefix + item_no ) ? 1 : 0;
            }
        }
    }
    return;
}
function check_allnone ( button, id_prefix ) {
    // sets all checkboxes (with the stated id prefix) checked or not according to button checked or not
    if ( button == undefined ) return;
    var miform = button.form;
    var pref_len = id_prefix.length;
    var new_checked = button.checked;
    var elems_len = miform.elements.length;
    for ( i=1; i<elems_len; i++ ) {
        var miobj = miform.elements[i];
        if ( miobj.type == 'checkbox' ) {
            if ( pref_len == 0 || id_prefix == miobj.id.substr(0,pref_len) ) {
                miobj.checked = new_checked;
            }
        }
    }
    return;
}
function imgbox_fit(img, box, minimaxi, align, tilt, rotated) {
    // align = 0100: 0/100%, 3070: 30/70%, 5050: 50/50%, 1000: 100/0%
    // tilt = degrees of image tilt; rotated: image is displayed rotated by 90 or 270 degrees (IE only)
    if ( minimaxi == undefined || minimaxi != 1 ) minimaxi = 0;
    var digits_regex = /^\d\d\d\d$/;
    if ( align == undefined || ! digits_regex.test(align) ) align = '5050';
    var align_prop;
    if ( align == '0100' ) {
        align_prop = 0;
    } else if ( align == '1000' ) {
        align_prop = 1;
    } else {
        align = align.toString();
        var in_first = align.substr(0,2);
        var in_sec = align.substr(2,2);
        if ( ! in_first + in_sec == 100 ) {
            in_first = 50;
            in_sec = 50;
        }
        align_prop = in_first / 100;
    }
    if ( tilt == null ) tilt = 0;
    var tilt_rad = tilt / 57.2957;
    if ( rotated == null ) rotated = 0;
    var img_width = strip_units(img.style.width); // img
    var img_height = strip_units(img.style.height);
    var img_prop = img_width / img_height;
    var box_width = strip_units(box.style.width); // box
    var box_height = strip_units(box.style.height);
    var box_prop = box_width / box_height;
    var true_boxh = box_height;
    var true_boxw = box_width;
    if ( rotated ) {
        var aux = box_width;
        box_width = box_height;
        box_height = aux;
    }
    var new_width = Math.round(box_width * Math.cos(tilt_rad) + box_height * Math.sin(tilt_rad));
    var new_height = Math.round(new_width / img_prop);
    if ( (minimaxi == 0 && new_height > Math.round(box_height * Math.cos(tilt_rad) + box_width * Math.sin(tilt_rad)) )
            || (minimaxi == 1 && new_height < Math.round(box_height * Math.cos(tilt_rad) + box_width * Math.sin(tilt_rad))) )
    {
        // new_height = box_height;
        new_height = Math.round(box_height * Math.cos(tilt_rad) + box_width * Math.sin(tilt_rad));
        new_width = Math.round(new_height * img_prop);
    }
    if ( rotated ) {
        var new_left = Math.round( ((true_boxw * Math.cos(tilt_rad) + true_boxh * Math.sin(tilt_rad)) - new_height - true_boxh * Math.sin(tilt_rad)) * align_prop );
        var new_top = Math.round( (true_boxh - new_width - true_boxw * Math.cos(tilt_rad) * 0) * align_prop );
    } else {
        var new_left = Math.round( ((box_width * Math.cos(tilt_rad) + box_height * Math.sin(tilt_rad)) - new_width - box_height * Math.sin(tilt_rad)) * align_prop );
        var new_top = Math.round( (box_height - new_height - box_width * Math.cos(tilt_rad) * 0) * align_prop );
    }
    img.style.width = new_width + 'px';
    img.style.height = new_height + 'px';
    img.style.left = new_left + 'px';
    img.style.top =  new_top + 'px';
}
function show_csspopup ( my_ob, max_width ) {
    // displays as a popup element just below this object when called onEvent="show_csspopup(this)", ids must be "sdiori_whatever" and "sdipup_whatever"
    // max_width added cause IE doesnt support CSS max-width property
    var shadow_shift = 3;
    var scroll_spare = 15;
    var ori_name = my_ob.id;
    var ori_root = ori_name.substr(0, 7);
    if ( ori_root == 'sdiori_' ) {
        var ori_pos = findPosition(my_ob);
        var ori_left = ori_pos[0] + document.body.scrollLeft;
        var ori_top = ori_pos[1] + document.body.scrollTop;
        var ori_width = my_ob.offsetWidth;
        var ori_height = my_ob.offsetHeight;
        var ori_no = ori_name.substr(7);
        var pup_obj = document.getElementById('sdipup_'+ori_no);
        var pup_left = Math.ceil(ori_left + ori_width / 4);
        var pup_top = ori_top + ori_height;
        pup_obj.style.display = 'block';
        pup_obj.style.zIndex = '-1';
        var pup_width = pup_obj.offsetWidth;
        if ( max_width != undefined && typeof(max_width) == 'number' && max_width > 0 ) {
            if ( pup_width > max_width ) {
                pup_obj.style.width = max_width.toString() + 'px';
                pup_width = pup_obj.offsetWidth;
            }
        }
        var pup_height = pup_obj.offsetHeight;
        var pup_extreme_x = pup_left + pup_width + shadow_shift;
        var pup_extreme_y = pup_top + pup_height + shadow_shift;
        var win_dims = wininner_size();
        var win_width = win_dims[0] - scroll_spare;
        if (document.documentElement && document.documentElement.scrollTop) {
            win_scroll_left = document.documentElement.scrollLeft;
            win_scroll_top = document.documentElement.scrollTop;
        } else if (document.body) {
            win_scroll_left = document.body.scrollLeft;
            win_scroll_top = document.body.scrollTop;
        }
        var win_height = win_dims[1] - scroll_spare;
        if ( pup_extreme_x > win_width + win_scroll_left ) {
            pup_left = win_width - pup_width + scroll_spare;
        }
        if ( pup_extreme_y > win_height + win_scroll_top ) {
            pup_top = ori_top - pup_height - shadow_shift;
        }
        pup_obj.style.left = pup_left + 'px';
        pup_obj.style.top = pup_top + 'px';
        pup_obj.style.zIndex = '1';
        var shadow_obj = document.getElementById('sdi_shadow');
        if ( shadow_obj == undefined ) {
            var shadow_new = document.createElement('span');
            shadow_new.setAttribute('id', 'sdi_shadow');
            shadow_new.style.backgroundColor = 'red';
            document.body.appendChild(shadow_new);
            shadow_obj = document.getElementById('sdi_shadow');
            shadow_obj.style.position = 'absolute';
            shadow_obj.style.backgroundColor = 'black';
            shadow_obj.style.filter = 'alpha(opacity=30)';
            shadow_obj.style.opacity = '.30';
        }
        shadow_obj.style.width = pup_width.toString() + 'px';
        shadow_obj.style.height = pup_height.toString() + 'px';
        shadow_obj.style.left = (pup_left + shadow_shift).toString() + 'px';
        shadow_obj.style.top = (pup_top + shadow_shift).toString() + 'px';
        shadow_obj.style.display = 'block';
    }
    return;
}
function hide_csspopup ( my_ob ) {
    var ori_name = my_ob.id;
    var ori_root = ori_name.substr(0, 7);
    if ( ori_root == 'sdiori_' ) {
        var ori_no = ori_name.substr(7);
        var popup_obj = document.getElementById('sdipup_'+ori_no);
        popup_obj.style.display = 'none';
        var shadow_obj = document.getElementById('sdi_shadow');
        shadow_obj.style.display = 'none';
    }
}
function accents2entities ( my_str ) {
    if ( my_str == undefined || my_str == '' ) return '';
    my_str = my_str.replace(/á/g,"%26aacute;");
    my_str = my_str.replace(/é/g,"%26eacute;");
    my_str = my_str.replace(/í/g,"%26iacute;");
    my_str = my_str.replace(/ó/g,"%26oacute;");
    my_str = my_str.replace(/ú/g,"%26uacute;");
    my_str = my_str.replace(/ñ/g,"%26ntilde;");
    my_str = my_str.replace(/Ñ/g,"%26Ntilde;");
    var output = my_str;
    return output;
}
function inspect(elm){
  var str = '';
  for (var i in elm){
    str += i + ": " + elm.getAttribute(i) + "\n";
  }
  alert(str);
}
function wininner_size() {
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) { //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [ myWidth, myHeight ];
}
function GetXmlHttpObject(handler) { 
    var objXMLHttp=null;
    if (window.XMLHttpRequest) {
        objXMLHttp=new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
}
function ac_selectIt(sel, text_field) { // ac (autocomplete) function
    var selobj = document.getElementById(sel);
    if ( ! selobj ) return;
    var in_text = text_field.value;
    if ( in_text ) {
        // alert('entro ' + in_text);
        var reg = new RegExp('^'+in_text,"i");
        var options_list = selobj.options;
        var options_len = options_list.length;
        var found = false;
        var i = 0;
        while ( ! found && i < options_len ) {
            if( reg.test(options_list[i].text) ) {
                found = true;
                selobj.selectedIndex = i;
            }
            i++;
        }
    } else {
        selobj.selectedIndex = 0;
    }
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function setCookie(c_name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
