String.prototype.trim = function(){return
(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

function IsNumeric(sText){
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++){
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1){
            IsNumber = false;
        }
    }
    return IsNumber;
}

/*
height
Defines the height of the window in pixels. Percentage values don't work.
width
Defines the width. Again, you'll have no joy with percentages.
left
Supported by version 4 browsers and above, this sets how far removed the window appears from the left of the screen. In pixels.
top
Partner to left, this pushes the window off the top of the screen.
resizable
Set to true or false, this may allow the user to resize the window.
scrollbars
Another Boolean value, this adds scrollbars to the new window. If your content may be longer then the dimensions you've specified, make sure this is set to yes.
toolbar
Specifies whether the basic back/forward toolbar should be visible. If there are links to follow in your new page, set this to yes.
menubar
Specifies whether the main toolbar (File, Edit, ...) is shown.
location
Specifies whether the location toolbar (address bar) is shown.
status
Specifies whether the new window can have a status bar. Best set to yes. For security reasons, Mozilla-based browsers always show the status bar.
*/
var popNWindow;
function popWindow(url, name, height, width, left, top, resizable, scrollbars, toolbar, menubar, location, status)
{
	popNWindow = window.open(url, name, 'height='+height+',width='+width+',left='+left+',top='+top+',resizable='+resizable+',scrollbars='+scrollbars+',toolbar='+toolbar+',menubar='+menubar+',location='+location+',status='+status);
	if (window.focus) {popNWindow.focus()}
}

function popCuteEditor(s_webFolder, s_saveField, s_tempField, s_section, s_photosFolder, s_photosField)
{
    var w = 850;
    var h = 600;
    var LeftPosition = (screen.width)?(screen.width-w)/2:0;
    var TopPosition = (screen.height)?(screen.height-h)/2:0;
    popWindow(s_webFolder+'/modules/weditor.php?sf='+s_saveField+'&tf='+s_tempField+'&sec='+s_section+'&pap='+s_photosFolder+'&pf='+s_photosField+'&wf='+s_webFolder, 'weditor', h, w, LeftPosition, TopPosition, 'yes', 'yes', 'no', 'no', 'no', 'yes')
}

function checkbox_switch_by_id(id)
{
    var val = 0;
    if(document.getElementById(id).checked == 1){ val = 0; }else{ val = 1; }
    document.getElementById(id).checked = val;
}

function goto_uri(uri)
{
    location.href = uri;
}

function trim(s)
{
    return s.replace(/^\s+/g,"").replace(/\s+$/g,"");
}

function check_user_name(name)
{
	//Expresión reglada
	var er_nombre = /^[a-z\A-Z\0-9\-_]{3,15}$/;
	//Retornar resultado de la comprobación
	return er_nombre.test(name);
}

function change_className(eleId, className){
    document.getElementById(eleId).className = className;
}

function switch_className(po, className1, className2){
    var ele = (typeof(po) != 'object')?document.getElementById(po):po;
    ele.className = (ele.className == className1)?className2:className1;
}

function get_field_value(id){
    return document.getElementById(id).value;
}
function set_field_value(id, value){
    document.getElementById(id).value = value;
}

function get_field_prop(id, prop){
    var scode = "document.getElementById('"+id+"')."+prop;
    return eval(scode);
}
function set_field_prop(id, prop, val){
    val = (IsNumeric(val))?val:"'"+val+"'";
    var scode = "document.getElementById('"+id+"')."+prop+"="+val;
    return eval(scode);
}

function hide_element(element_id){
	var ele = document.getElementById(element_id);
	ele.style.display = "none";
}
function show_element(element_id){
	var ele = document.getElementById(element_id);
	ele.style.display = "";
}
function switch_display(element_id){
	var ele = document.getElementById(element_id);
        if(ele == null) return;
	ele.style.display = (ele.style.display == "none")?"":"none";
}

var getXhr = function(){
	var xhr;

	return function(){
		if (xhr) return xhr;

		if (typeof XMLHttpRequest !== 'undefined') {
			xhr = new XMLHttpRequest();
		} else {
			var v = [
				"Microsoft.XmlHttp",
				"MSXML2.XmlHttp.5.0",
				"MSXML2.XmlHttp.4.0",
				"MSXML2.XmlHttp.3.0",
				"MSXML2.XmlHttp.2.0"
			];

			for (var i=0; i < v.length; i++){
				try {
					xhr = new ActiveXObject(v[i]);
					break;
				} catch (e){}
			}
		}

		return xhr;
	}
}();
function ajaxNew() {
    
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
    

    /*
    var xmlhttp = false;
    var v = [
        "Microsoft.XmlHttp",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0"
    ];
    for (var i=0; i < v.length; i++){
        try {
            xmlhttp = new ActiveXObject(v[i]);
            break;
        } catch (e){
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        alert('pasa por XMLHttpRequest()');
        xmlhttp = new XMLHttpRequest();
    }
    alert('xmlhttp: '+xmlhttp);
    return xmlhttp;
    */
}
function ajaxWriteData2(source, divID) {
    contenedor = document.getElementById(divID);
    ajax = ajaxNew();
    ajax.open('GET', source, false);
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
            contenedor.innerHTML = ajax.responseText;
        }
    }
    ajax.send(null);
}
function ajaxWriteData(source, divID) {
    contenedor = document.getElementById(divID);
    if(contenedor == null) return false;
    var xhr = getXhr();
    xhr.open('GET', source, false);
    xhr.send('');
    contenedor.innerHTML = xhr.responseText;
    return xhr.responseText;
}
function ajaxGetData2(source) {
    var result = null;
    ajax = ajaxNew();
    ajax.open('GET', source, false);
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
            result = ajax.responseText;
        }
        alert('estado: '+ajax.readyState);
    }
    ajax.send(null);
    return result;
}
function ajaxGetData(source) {
    var xhr = getXhr();
    xhr.open('GET', source, false);
    xhr.send('');
    return xhr.responseText;
}
function ajaxTask2(source, evalCode) {
    ajax = ajaxNew();
    ajax.open('GET', source, false);
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
            eval(evalCode);
        }
    }
    ajax.send(null);
}
function ajaxTask(source, evalCode) {
    var xhr = getXhr();
    xhr.open('GET', source, false);
    xhr.send('');
    eval(evalCode);
}

var sending_email = 0;
function contact_set(web_folder, level_id){
    ajaxWriteData(web_folder+'/ajax_func.php?func_name=get_contact_form&level_id='+level_id, 'upper_layer_content_container_bottom');
}
function send_mail(web_folder, to, name, surnames, email, subject, message, onComplete, onError){
    sending_email = 1;
    var url;
    url = web_folder+'/ajax_func.php?func_name=send_mail';
    url+= '&to='+to;
    url+= '&name='+name;
    url+= '&surnames='+surnames;
    url+= '&email='+email;
    url+= '&subject='+subject;
    //url+= '&message='+message;
    url+= '&message='+message.replace(/\n/gi, "[-br-]");

    //var ecode = (response_container != '')?'document.getElementById(\''+response_container+'\').innerHTML=xhr.responseText;':'';
    //ajaxTask(url, ecode);

    var result = ajaxGetData(url);
    if(result == 1){
        result = 'e-Mail enviado satisfactoriamente.<br />Se ha enviado un mensaje de confirmación a la cuenta indicada.';
        eval(onComplete);
        //eval(onError);
    }else{
        eval(onError);
    }
    sending_email = 0;
}
function email_check(emailStr) {
    var checkTLD=1;
    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat=/^(.+)@(.+)$/;
    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars="\[^\\s" + specialChars + "\]";
    var quotedUser="(\"[^\"]*\")";
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray=emailStr.match(emailPat);

    if (matchArray==null) {
        return "Tu dirección de correo no aparece o es incorrecta (comprueba @ y .'s)";
    }

    var user=matchArray[1];
    var domain=matchArray[2];
    for (i=0; i<user.length; i++) {
        if (user.charCodeAt(i)>127) {
            return "Tu dirección de correo contiene caracteres no validos.";
        }
    }
    for (i=0; i<domain.length; i++) {
        if (domain.charCodeAt(i)>127) {
            return "El dominio de la dirección introducida contiene caracteres no validos.";
        }
    }
    if (user.match(userPat)==null) {
        return "La dirección de correo parece incorrecta, por favor compruebalo.";
    }

    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
        for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                return "La dirección IP de destino no es correcta!";
            }
        }
        return true;
    }

    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    for (i=0;i<len;i++) {
        if (domArr[i].search(atomPat)==-1) {
            return "La dirección de correo parece incorrecta, por favor compruebalo, incluyendo comas ',' o puntos '.' al final de la dirección.";
        }
    }
    if (checkTLD && domArr[domArr.length-1].length!=2 &&
    domArr[domArr.length-1].search(knownDomsPat)==-1) {
        return "Tu dirección de correo debe terminar en un dominio o dos letras " + "país.";
    }
    if (len<2) {
        return "Falta el nombre del host en su dirección de correo. Compruebe que no haya ningún espacio en blanco al final de la dirección.";
    }
    return true;
}

function subscriptions_send(web_folder, eres_id, section, element){
    contenedor = document.getElementById(eres_id);
    if(contenedor == null) return;
    //var extext = contenedor.innerHTML;
    contenedor.innerHTML = 'Enviando...';
    var result = ajaxGetData(web_folder+'/ajax_func.php?func_name=subscriptions_send&section='+section+'&element='+element, eres_id);
    //contenedor.innerHTML = extext + result.split(',')[0];
    contenedor.innerHTML = result.split(',')[0];
    if(result.split(',')[1] != '') contenedor.innerHTML += '<hr>' + result.split(',')[1];
}
function subscriptions_info(web_folder, eres_id, section, element){
    contenedor = document.getElementById(eres_id);
    if(contenedor == null) return;
    contenedor.innerHTML = 'Cargando información...';
    var result = ajaxGetData(web_folder+'/ajax_func.php?func_name=subscriptions_info&section='+section+'&element='+element, eres_id);
    contenedor.innerHTML = result;
}

function photo_albums_links_set(web_folder, nicEditor){
    var str = '';
    var link_name = '';
    var ar_albums = ajaxGetData(web_folder+'/ajax_func.php?func_name=get_folder_elements&folder_path=photos').split(',');
    for(i=0; i <= ar_albums.length-1; i++){
        //str += '<div><a href="#" onclick="javascript:photo_albums_links_open(\''+web_folder+'\', \''+ar_albums[i]+'\', \''+nicEditor+'\');return false;">' + ar_albums[i] + '</a></div>';
        link_name = ar_albums[i].split('_', 1)[0];
        str += '<div><a href="#" onclick="javascript:photo_albums_links_open(\''+web_folder+'\', \''+ar_albums[i]+'\', \''+nicEditor+'\');return false;">' + ar_albums[i].substring(link_name.length+1) + '</a></div>';
        //str += '<div>' + ar_albums[i].split('_')[1] + '</div>';
    }
    //$('#added_albums').html(str);
    var album_conteiner = document.getElementById('added_albums');
    album_conteiner.innerHTML = str;
}
function photo_albums_links_open(web_folder, album_path, nicEditor){
    var album_player = document.getElementById('upper_layer_content_photo_album_edit_bottom');
    album_player.innerHTML = '';
    //Obtener imágenes
    var src = '';
    var ar_images = ajaxGetData(web_folder+'/ajax_func.php?func_name=get_folder_elements&folder_path=photos/'+album_path).split(',');
    for(i=0; i <= ar_images.length-1; i++){
        if(ar_images[i] != 'data.txt' && !ar_images[i].startsWith('thumb')){
            src = web_folder+'/photos/'+album_path+'/'+ar_images[i];
            album_player.innerHTML += '<img src="'+web_folder+'/photos/'+album_path+'/thumb-'+ar_images[i]+'" alt="photo_'+i+'" style="cursor:pointer;" onclick="javascript:niceditInsertImage(\''+nicEditor+'\', \''+src+'\');upper_layer_hide(\'upper_layer_back_photo_album_edit\', \'upper_layer_content_photo_album_edit\');" />';
        }
    }
    upper_layer_pos_photo_album_edit();
    upper_layer_show('upper_layer_back_photo_album_edit', 'upper_layer_content_photo_album_edit');
}
function niceditInsertImage(nicEditor, src){
    //var editor = nicEditors.findEditor(nicEditor);
    //var img_tag = '';
    //img_tag = '<img src="'+src+'" width="40%" height="40%" alt="texto alternativo" />';
    //editor.setContent(editor.getContent() + img_tag);

    var onComplete = 'var limg = new Image();limg.src = \''+src+'\';\n\
                    var img_tag = \'<img src="'+src+'" style="WIDTH: \'+(limg.width/2)+\'px; HEIGHT: \'+(limg.height/2)+\'px" alt="texto alternativo" />\';\n\
                    var editor = nicEditors.findEditor(\''+nicEditor+'\');\n\
                    editor.setContent(editor.getContent()+img_tag);';
    iLoadTask(src, onComplete);
    
    /*
    var onComplete = 'var limg = new Image();limg.src = \''+src+'\';\n\
                    var img_tag = \'<img src="'+src+'" width="\'+(limg.width/2)+\'" height="\'+(limg.height/2)+\'" alt="texto alternativo" />\';\n\
                    var editor = nicEditors.findEditor(\''+nicEditor+'\');\n\
                    editor.setContent(editor.getContent()+img_tag);alert(\'sale\');';
    alert(onComplete);
    iLoadTask(src, onComplete);
    */
}

/*
var t;
function scroll_div_auto(div_id, px){
  var div = document.getElementById(div_id);
  if (div.scrollTop>0){
     div.scrollTop = div.scrollTop + px;
     sfunc = 'scroll_div(\''+div_id+'\','+px+')';
     t = setTimeout(sfunc, 10);
  }
  else clearTimeout(t);
}
*/
function scroll_div(div_id, px, div_height){
	var div = document.getElementById(div_id);
	if (((px<0 && div.scrollTop>=Math.abs(px))) || (px>0 && div.scrollHeight-div_height-div.scrollTop>=px)){
		div.scrollTop = div.scrollTop + px;
	}
}

n_photo_inputs=0;
function create_photo_input(container, obj, type, id,  name, value) {
    n_photo_inputs++;
    fi = document.getElementById(container); // 1
    contenedor = document.createElement('div'); // 2
    contenedor.id = 'div'+n_photo_inputs; // 3
    //fi.appendChild(contenedor); // 4
    //fi.insertBefore(contenedor,obj); // 4
    prev = document.getElementById('div'+(n_photo_inputs-1));
    fi.insertBefore(contenedor, prev); //añadir al principio

    ele = document.createElement('input'); // 5
    ele.type = type; // 6
    ele.value = value;
    //ele.name = 'photo_'+n_photo_inputs; // 6
    //ele.name = 'photos[]'; // 6
    if(id != '') ele.id = id;
    ele.name = name;
    ele.className = 'frm_text add';
    contenedor.appendChild(ele); // 7

    if(type != 'hidden'){
        ele = document.createElement('input'); // 5
        ele.type = 'button'; // 6
        ele.value = 'Borrar'; // 8
        ele.name = 'div'+n_photo_inputs; // 8
        ele.className = 'frm_text delete';
        ele.onclick = function () {remove_photo_input(container, this.name)} // 9
        contenedor.appendChild(ele); // 7
    }
}
function remove_photo_input(container, obj) {
  fi = document.getElementById(container); // 1
  fi.removeChild(document.getElementById(obj)); // 10
}


var editorial_message = function() {
    this.aTimer = null; //timer
    this.wTimer = null; //timer de espera
    this.ele = null; //elemento con el que se trabajará
    this.eleH = null; //altura del elemento en pixels
    this.eleTitle = null;
    this.eleLink = null;
    this.secs = null; //milisegundos que se mantendrá una vez mostrado
    this.pixstep = null; //cantidad de pixels que se desplaza por movimiento
    this.cPos = null;
    this.wasShown = null;
    this.mustWait = null;

    return {
        init : function(ele, eleH, secs, pixstep) {
            editorial_message.ele = document.getElementById(ele);
            editorial_message.eleH = eleH;
            editorial_message.eleTitle = document.getElementById('editorial_layer_title');
            editorial_message.eleLink = document.getElementById('editorial_layer_link');
            editorial_message.secs = secs;
            editorial_message.pixstep = pixstep;
        },

        start : function() {
            if (!editorial_message.aTimer){
                editorial_message.aTimer = setInterval("editorial_message.step()", 5);
                editorial_message.wasShown = 0;
                editorial_message.cPos = 1;
                editorial_message.mustWait = 0;
                //editorial_message.ele.style.display = "";
                //editorial_message.ele.style.fontSize = "0px";
                editorial_message.eleTitle.style.fontSize = "0px";
                editorial_message.eleLink.style.fontSize = "0px";
                editorial_message.eleLink.style.display = "none";
            }
        },

        stop : function() {
            if(editorial_message.aTimer){
                window.clearInterval(editorial_message.aTimer);
                editorial_message.aTimer = null;
                //editorial_message.ele.style.display = "none";
                //editorial_message.ele.style.fontSize = "0px";
                editorial_message.eleTitle.style.fontSize = "0px";
                editorial_message.eleLink.style.fontSize = "0px";
                editorial_message.eleLink.style.display = "none";
            }
        },
        
        step : function() {
            if(!editorial_message.mustWait){
                if(editorial_message.cPos < editorial_message.eleH && !editorial_message.wasShown){
                    editorial_message.cPos += editorial_message.pixstep;
                }else{
                    editorial_message.cPos -= editorial_message.pixstep;
                }

                editorial_message.ele.style.height = editorial_message.cPos+'px';
                
                if(editorial_message.cPos < 10) {
                    //editorial_message.ele.style.fontSize = "0px";
                    editorial_message.eleTitle.style.fontSize = "0px";
                    editorial_message.eleLink.style.fontSize = "0px";
                    editorial_message.ele.style.paddingBottom = "0px";
                }
                if(editorial_message.cPos >= 10) {
                    //editorial_message.ele.style.fontSize = e ditorial_message.cPos;
                    if (editorial_message.cPos < 39) editorial_message.eleTitle.style.fontSize = editorial_message.cPos+'px';
                    if (editorial_message.cPos < 20) editorial_message.eleLink.style.fontSize = editorial_message.cPos+'px';
                    editorial_message.ele.style.paddingBottom = "5px";
                }

                if(editorial_message.cPos >= 35){
                    editorial_message.eleLink.style.display = "";
                }else{
                    editorial_message.eleLink.style.display = "none";
                }


                if(editorial_message.cPos == editorial_message.eleH && !editorial_message.wasShown){
                    editorial_message.wasShown = 1;
                    editorial_message.mustWait = 1;
                    editorial_message.wTimer = setTimeout("editorial_message.mustWait = 0", editorial_message.secs);
                }

                if(editorial_message.cPos == 1 && editorial_message.wasShown){
                    editorial_message.stop();
                }
            }
        }
    };
}();

/*
function cpicker_get_panel(){
    //var strp = '';
    document.write("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border: 1px solid black;\">");
    StepH = 20;
    var StepV = 8;
    var i=0;
    var a=0;
    for (a=0;a<=255; a+=StepV){
    cpicker_WriteRow(a,i);
    }
    a=255;
    for (i=0; i<=255; i+=StepV){
    cpicker_WriteRow(a,i);
    }
    document.write("</table>");
    //return strp
}
function cpicker_Hexa(Dec){
var nb = Dec.toString(16);
if (nb.length < 2) {nb = "0" + nb;}
return(nb);
}
function cpicker_GradientPart(dr, dg, db, fr, fg, fb, Step) {
cr=dr;cg=dg;cb=db;
sr=((fr-dr)/Step);
sg=((fg-dg)/Step);
sb=((fb-db)/Step);
var Result = '';
for (var x = 0; x <= Step; x++) {
var cmd = " onclick=\"alert(this);document.getElementById('ColorCode').value=this.bgColor;alert('sale');\" onmouseover=\"document.getElementById('ColorShow').style.backgroundColor=this.bgColor;\"";
Result += "<td class=\"ColorCell\" style=\"background-color:#" + cpicker_Hexa(Math.floor(cr)) + cpicker_Hexa(Math.floor(cg)) + cpicker_Hexa(Math.floor(cb)) + "\"" + cmd + "></td>";
cr += sr; cg += sg; cb += sb;
}
//alert(Result);
return(Result);
}
function cpicker_WriteRow(a,i){
document.write("<tr>");
document.write(cpicker_GradientPart(a,i,i, a,a,i, StepH));
document.write(cpicker_GradientPart(a,a,i ,i,a,i, StepH));
document.write(cpicker_GradientPart(i,a,i, i,a,a, StepH));
document.write(cpicker_GradientPart(i,a,a, i,i,a, StepH));
document.write(cpicker_GradientPart(i,i,a, a,i,a, StepH));
document.write(cpicker_GradientPart(a,i,a, a,i,i, StepH));
document.write("</tr>");
}
*/
