

var xmlHttp;
var xmlHttpCount;

function Show(divId, topPosition ) {
    
    Cover(document.getElementById('CapaNavegacion'), document.getElementById(divId),topPosition, true);
    
    document.getElementById(divId).style.display = "block";

}

function popup(mylink, windowname, ancho, largo) {
  
    if (!window.focus) return true;

    var href;

   
    if (typeof (mylink) == 'string')
        href = mylink;
    else
        href = mylink.href;
    if (ancho && largo) {
      
        window.open(href, windowname, 'width=' + ancho + ' height=' + largo + ',scrollbars=yes,resizable=1');
    }
    else {
    
        window.open(href, windowname, 'resizable=1');
    } 
        
    return false;
}

function msgBox(message)
{   var msgbox = document.getElementById('msgbox');
    msgbox.innerHTML =message;
    var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2); 
      var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2);
      msgbox.style.top = y; 
      msgbox.style.left = x;
      msgbox.style.display = "block";
 }

 function addLoadEvent(func) {
     var oldonload = window.onload;
     if (typeof window.onload != 'function') {
         window.onload = func;
     } else {
         window.onload = function() {
             if (oldonload) {
                 oldonload();
             }
             func();
         }
     }
 }

function Hide(divId) {
       
    document.getElementById(divId).style.display = "none";

}

function Cover(bottom, top, topPosition,ignoreSize) {        
    var location = Sys.UI.DomElement.getLocation(bottom);
    var x;  
    var y;

    top.style.position = 'absolute';

    var pantalla=DimensionesExplorador();
        
    alert(top.style.width);
    
    top.style.top = topPosition + 'px';
    top.style.left = pantalla.x-500 + 'px';
                
    if (!ignoreSize) {
        top.style.height = bottom.offsetHeight + 'px';
        top.style.width = bottom.offsetWidth + 'px';
    }
}

function DimensionesExplorador(){

    var d = document;
    var winWidth;  
    var winHeight;
    
    if (typeof window.innerWidth != 'undefined') {
        winWidth = window.innerWidth;
        winHeight = window.innerHeight;
    } 
    else {
        if (d.documentElement &&   typeof d.documentElement.clientWidth != 'undefined' && d.documentElement.clientWidth != 0) {
            winWidth = d.documentElement.clientWidth;
            winHeight = d.documentElement.clientHeight;
            }      
        else {
                if (d.body &&  typeof d.body.clientWidth != 'undefined') {
                    winWidth = d.body.clientWidth;
                    winHeight = d.body.clientHeight;
                    }
               }
       }

       //alert(winWidth);
       //alert(winHeight);

       return {x:winWidth,y:winHeight};
       
}

function AnalizarSms(Mensaje)
{
    var cResultado
    var aResultado

    cResultado = Mensaje;
       
    xmlHttpCount = GetXmlHttpObject();
	
	if (xmlHttpCount == null) {
	   
		return;
	}
	
	var url = "/Panel/Mobile/SMSAnaliza.aspx?mensaje=" + encodeURIComponent(Mensaje);

	try {
	
	    xmlHttpCount.onreadystatechange = stateChangedCount;
	    xmlHttpCount.open("GET", url, true,"","");
	    xmlHttpCount.send(null);

	    //cResultado = xmlHttpCount.responseText;
	    	    
	}
	catch (e) {
	    alert(e);	    
	}
			
	return cResultado;
		
}

function URLGet(){

    return window.location.href;

}

function URLGetWithoutQueryString(){

    var url=URLGet();
    
    var URI = url.split("?");
    
    return URI[0];
    
}


function URLGetFullQueryString(){

    var url = URLGet();
        
    var URI = url.split("?");
    
    return URI[1];
               
}


function URLGetQuerystringParam(name) {

    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    
    if (results == null)
        return "";
    else
        return results[1];
}
 
 
function URLTracking() {
    var cTrackUrl
    var aResultado

    var url= URLGetWithoutQueryString();

    var param = URLGetFullQueryString();
           
    cTrackUrl = "/Codigo/URLTracking.aspx?url=" + encodeURIComponent(url) + "&param=" + encodeURIComponent(param);

    AbreURL(cTrackUrl);

}


function AbreURL(url) {

    var cResultado;
    
    xmlHttpCount = GetXmlHttpObject();

    if (xmlHttpCount == null) {

        return;
    }

    try {
        xmlHttpCount.open("GET", url, true, "", "");
        xmlHttpCount.send(null);
        cResultado = xmlHttpCount.responseText;
        
    }
    catch (e) {
        alert(e);
    }

    return cResultado;
    
}


function stateChangedCount() {
    
    //alert('estado');
    var cResultado
    var aResultado
    
    if (xmlHttpCount.readyState == 4) {

        cResultado = xmlHttpCount.responseText
        
        aResultado = cResultado.split("]");
        cResultado = aResultado[0];

        aResultado = cResultado.split(",");

        //alert(cResultado);

        cResultado = aResultado[0] + "<br />" + aResultado[1] + "<br />" + aResultado[2];

      
        setInnerHTML("CapaResultadoAnalisis", cResultado);
	    
	}
}

function stateChanged() {
	if (xmlHttp.readyState==4) {

		setInnerHTML("listpost", xmlHttp.responseText);
	}
}

function setInnerHTML(namn, txt) {
    var el = document.getElementById(namn);
    el.innerHTML = txt;
}

function FactoryXMLHttpRequest() {

  if (window.XMLHttpRequest) {
        
    return new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    var msxmls = new Array(
                   'Msxml2.XMLHTTP.5.0',
                   'Msxml2.XMLHTTP.4.0',
                   'Msxml2.XMLHTTP.3.0',
                   'Msxml2.XMLHTTP',
                   'Microsoft.XMLHTTP');

    for (var i = 0; i < msxmls.length; i++) {
        try {
            
            return new ActiveXObject(msxmls[i]);
      }
      catch (e) {}
    }
  }
  throw new Error("Could not instantiate XMLHttpRequest");
}


function GetXmlHttpObject() {
	var xmlHttpThis=null;

	xmlHttpThis = new FactoryXMLHttpRequest;

	return xmlHttpThis;
}

function IsNumeric(sText) {
	var ValidChars = "0123456789+- ";
	var Char;
	for (i = 0; i < sText.length; i++) { 
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			return false;
		}
	}
	return true; 
}

function ElementStringToLocalTime(elementID)
   {
   var element = document.getElementById(elementID);
   var timeString = element.value;
                                 
   var utcTime = new Date();
   utcTime = ParseTimeStringAsUTCTime(timeString);
      
   element.value = FormatTime(utcTime);
  }
  
  function CopyElementToUTCTimeElement(sourceElementID, destinationElementID)
  {
  var SourceElement = document.getElementById(sourceElementID);
  var DestinationElement = document.getElementById(destinationElementID);
  
    var timeString = SourceElement.value;
                                 
  var Time = new Date();
  Time = ParseTimeStringAsLocalTime(timeString);
    DestinationElement.value = FormatUTCTime(Time); 
  }
   
  function AddLeadingZero(num)
 {
  if( num < 10)
  {
     return '0' + num;
    }
    return num;
 }
 
function FormatTime(time)
 {
 //returns string from a Date object in the following format "2008-05-07 21:15"
   return time.getFullYear() + '-' + AddLeadingZero(time.getMonth()) + '-' + AddLeadingZero(time.getDate()) + ' ' + AddLeadingZero(time.getHours()) + ':' + AddLeadingZero(time.getMinutes());
   }

 function FormatUTCTime(time)
 {
  //returns string from a Date object in the following format "2008-05-07 21:15"
  return time.getUTCFullYear() + '-' + AddLeadingZero(time.getUTCMonth()) + '-' + AddLeadingZero(time.getUTCDate()) + ' ' + AddLeadingZero(time.getUTCHours()) + ':' + AddLeadingZero(time.getUTCMinutes());
}
 
 function ParseTimeStringAsLocalTime(timeString)
{
   //creates Date object based on string in the following format "2008-05-07 21:15"
   var numYear = parseInt(timeString.substring(0,4), 10);
   var numMonth = parseInt(timeString.substring(5,7),10);
 var numDay = parseInt(timeString.substring(8,10), 10);
  var numHour = parseInt(timeString.substring(11,13),10);
  var numMinute = parseInt(timeString.substring(14,16),10);
  var Time = new Date(numYear, numMonth, numDay, numHour, numMinute, 0, 0);
 return Time;
  }
 
function ParseTimeStringAsUTCTime(timeString)
 {
  //creates Date object based on string in the following format "2008-05-07 21:15"
  var numYear = parseInt(timeString.substring(0,4), 10);
 var numMonth = parseInt(timeString.substring(5,7),10);
 var numDay = parseInt(timeString.substring(8,10), 10);
  var numHour = parseInt(timeString.substring(11,13),10);
 var numMinute = parseInt(timeString.substring(14,16),10);
 
  var utcTime = new Date();
   
  utcTime.setUTCFullYear(numYear);
  utcTime.setUTCMonth(numMonth);
  utcTime.setUTCDate(numDay);
 utcTime.setUTCHours(numHour);
  utcTime.setUTCMinutes(numMinute);
  utcTime.setUTCSeconds(0);
  utcTime.setUTCMilliseconds(0);
  return utcTime;
}

function getDocumentHeight() {
       if (document.body.scrollHeight && navigator.appVersion.indexOf('Win') != -1) {
           return 0; 
    		}
    else if (document.documentElement.scrollHeight) {
      return document.documentElement.scrollHeight;
    }
    else if (document.documentElement.offsetHeight) {
       return document.documentElement.offsetHeight;
    }
}

function Trim(input) {
    var lre = /^\s*/;
    var rre = /\s*$/;
    input = input.replace(lre, "");
    input = input.replace(rre, "");
    return input;
}

// filter the files before Uploading for text file only
function CheckForTestFile(oUpload) {

    var file = document.getElementById(oUpload);
    if (file) {
        alert('hola');
        var fileName = file.value;
        //Checking for file browsed or not 
        if (Trim(fileName) == '') {
            alert("Please select a file to upload!!!");
            file.focus();
            return false;
        }

        //Setting the extension array for diff. type of text files 
        var extArray = new Array(".txt", ".doc", ".rtf", ".pdf", ".sxw", ".odt",
                                    ".stw", ".html", ".htm", ".sdw", ".vor");

        //getting the file name
        while (fileName.indexOf("\\") != -1)
            fileName = fileName.slice(fileName.indexOf("\\") + 1);

        //Getting the file extension                     
        var ext = fileName.slice(fileName.indexOf(".")).toLowerCase();

        //matching extension with our given extensions.
        for (var i = 0; i < extArray.length; i++) {
            if (extArray[i] == ext) {
                return true;
            }
        }
        alert("Please only upload files that end in types:  "
               + (extArray.join("  ")) + "\nPlease select a new "
               + "file to upload and submit again.");
        file.focus();
    }
    return false;
} 


function xtractFile(data)
{
            data = data.replace(/^\s|\s$/g, ""); //trims string

            if (/\.\w+$/.test(data)) {
                if (data.match(/([^\/\\]+)\.(\w+)$/) )
                    return {filename: RegExp.$1, ext: RegExp.$2};
                else
                    return {filename: "no file name", ext:null};
            }
            else {
                if (data.match(/([^\/\\]+)$/) )
                    return {filename: RegExp.$1, ext: null};
                else
                    return {filename: "no file name", ext:null};                    
            }
        }


function Redirect(url,tipo,trueorfalse) {
    window.open(url, tipo);
    return trueorfalse;
}

function Redireccion(url) {

    window.location.href = url;
    return false;
}


function repeat(s, n) {
    var r = ""; for (var a = 0; a < n; a++) r += s;
    return r;
}

function padl(cCadena , cCaracter, nLongitud) {


    var MiCadena = cCadena+"";

    var nRepetir = nLongitud - MiCadena.length;
  
    if (nRepetir < 0) {
        nRepetir = 0;
    }

    cCadena = repeat(cCaracter, nRepetir) + cCadena;
    
    return (cCadena);
}

function padr(cCadena, cCaracter, nLongitud) {


    var MiCadena = cCadena + "";

    var nRepetir = nLongitud - MiCadena.length;

    if (nRepetir < 0) {
        nRepetir = 0;
    }

    cCadena = cCadena + repeat(cCaracter, nRepetir);

    return (cCadena);
}

/*Muestra la fecha y hora del cliente en formato largo dd/MM/yyyy hh:mm:ss*/

function MostrarFechaCliente() {
    
    var d = new Date()
    
    var gmtHoras = -d.getTimezoneOffset() / 60;
    var Dia = padl(d.getDate(), "0", 2);
    
    var Mes = padl(d.getMonth()+1, "0", 2); //From 0 to 11
    var Anyo = d.getFullYear();
    var Hora = padl(d.getHours(), "0", 2);

    var Minutos = padl(d.getMinutes(), "0", 2);
    var Segundos = padl(d.getSeconds(), "0", 2);

    return (Dia + "/" + Mes + "/" + Anyo + " " + Hora + ":" + Minutos + ":" + Segundos);

}

/*Devuelve la diferencia horaria respecto UTC/GMT del cliente*/

function HorasDiferenciaUTC() {

    var d = new Date()

    return (-d.getTimezoneOffset() / 60);

}

var TimeToFade = 500.0;

function fade(eid) {
    var element = document.getElementById(eid);
    if (element == null)
        return;

    if (element.style.visibility == 'hidden') {
        element.FadeState = -2; /*transparent->opaque*/
        element.style.opacity = '';
      
    }


        if (element.FadeState == null) {

            if (element.style.opacity == null
         || element.style.opacity == '1') {
                /* alert(element.style.opacity);*/
                element.FadeState = 2;
            }
            else {
                element.FadeState = -2;
            }
        }


        if (element.FadeState == 1 || element.FadeState == -1) {
            element.FadeState = element.FadeState == 1 ? -1 : 1;
            element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
        }
        else {
            /*alert('hola');*/
            if (element.FadeState != 2) {
                element.FadeState = element.FadeState == 2 ? -1 : 1;
                element.FadeTimeLeft = TimeToFade;
                clearTimeout(element.FadeTimer);
                element.FadeTimer=setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
            }
        }

    }

        
/*appear: 
    eid=element
    AnimateTime: milliseconds of appearing effect
    TopOpacit: stop when reached 0 to 1 (ex: 0.43, 0.95 etc.)
    */
function appear(eid,AnimateTime,TopOpacity) {
    var element = document.getElementById(eid);
    if (element == null)
        return;


    if (element.style.visibility == 'hidden' ||
         element.style.display == 'none' ||
             (element.style.visibility == '' && element.style.display=='')) {

           
            element.FadeState = -2; /*transparent->opaque*/

            element.style.display = 'block';
            element.style.visibility = 'visible';
            SetElemOpacity(element, '0')
                                 
            if (element.FadeState == 1 || element.FadeState == -1) {
                element.FadeState = element.FadeState == 1 ? -1 : 1;
                element.FadeTimeLeft = AnimateTime - element.FadeTimeLeft;
               
            }
            else {             
                
                clearTimeout(element.FadeTimer);
                
                if (element.FadeState != 2 || element.FadeState == '') {
                    element.FadeState = -1;
                    element.FadeTimeLeft = AnimateTime;
                    element.FadeTimer=setTimeout("animateAppear(" + new Date().getTime() + ",'" + eid + "'," + AnimateTime + "," + TopOpacity + ")", 33);
                }
                                 
            }          
    }
   
}

function SetElemOpacity(a, b) {
    if (a && a.style) {
        if (b == 1) {
            a.style.opacity = (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : null;
            if (/MSIE/.test(navigator.userAgent))
                if (a.style['filter']) a.style['filter'] = a.style['filter'].replace(/alpha\([^\)]*\)/gi, '')
            } 
        else {
                if (b < 0.00001) b = 0;
                                
                a.style['opacity'] = b;

                if (/MSIE/.test(navigator.userAgent)) {

                    if (b < 0.01) b = 0.01;
                    
                    a.style['filter'] = (a.style['filter'] ? a.style['filter'].replace(/alpha\([^\)]*\)/gi, '') : '') + 'alpha(opacity=' + b * 100 + ')'
                    /*setInnerHTML('feed1', a.style['filter']);*/
                    }
                }
        } 
   }


function animateAppear(lastTick, eid, AnimateTime,TopOpacity) {
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;

    var element = document.getElementById(eid);

   /*timeout, fully opaque*/

    if (element.style.visibility == 'hidden' ||
         element.style.display == 'none' ||
             (element.style.visibility == '' && element.style.display == '')) {
        element.FadeTimeLeft = elapsedTicks;
        
    }
    
    if (element.FadeTimeLeft <= elapsedTicks) {

        SetElemOpacity(element, TopOpacity);   
        element.FadeState = 2;
        clearTimeout(element.FadeTimer);
  
        return;
    }
    
  
    element.FadeTimeLeft -= elapsedTicks;

    var newOpVal = element.FadeTimeLeft / AnimateTime;

    newOpVal = 1 - newOpVal;

    /*setInnerHTML('feed', newOpVal);*/

    if (newOpVal <= TopOpacity) {
        SetElemOpacity(element, newOpVal);
       
        element.FadeTimer = setTimeout("animateAppear(" + curTick + ",'" + eid + "'," + AnimateTime + "," + TopOpacity + ")", 33);
    }
    else {
        /*Reached max opacity*/
        SetElemOpacity(element, TopOpacity);
        element.FadeState = 2;
        clearTimeout(element.FadeTimer);
        return;
    }
    
}

function animateFade(lastTick, eid) {
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;

    var element = document.getElementById(eid);

    if (element.FadeTimeLeft <= elapsedTicks) {
        element.style.opacity = element.FadeState == 1 ? '1' : '0';
        element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 1 ? '100' : '0') + ')';
        element.FadeState = element.FadeState == 1 ? 2 : -2;
        return;
    }

    element.FadeTimeLeft -= elapsedTicks;
    var newOpVal = element.FadeTimeLeft / TimeToFade;
    
    if (element.FadeState == 1)
        newOpVal = 1 - newOpVal;

    element.style.opacity = newOpVal;
    element.style.filter = 'alpha(opacity = ' + (newOpVal * 100) + ')';

    element.FadeTimer=setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}

function setOpacity(domId, val) {
    
    obj = document.getElementById(domId);
    obj.style.MozOpacity = val / 100;
    obj.style.opacity = val / 10;
    obj.style.filter = 'alpha(opacity=' + val * 5 + ')';
}

function efecto_fade(domId) {

    obj = document.getElementById(domId);
    if (obj.style.display == 'none') return false;
    var alpha = 50;
    function f() {
        alpha--;
        setOpacity(domId, alpha);
        if (alpha > -1) {
            setTimeout(f, 25);
        }
        else {
            /*obj.style.display = 'none';*/
        }
    }
    setTimeout(f, 25);
}

function efecto_appear(domId) {
    /*alert('1');*/
    obj = document.getElementById(domId);

    if (obj.style.visibility == 'visible') {
        obj.appeared = 1;
        /*alert('visible');*/                
    }

    if (obj.style.visibility == 'hidden') {
        obj.appeared = 0;
        /*alert('visible');*/
    }
    
    if (obj.appeared == null) {
        obj.appeared = 0;
        /*alert('null');*/
    }
    
    if(obj.appeared==0){
           
        setOpacity(domId, 0);

     
        
        /*obj.style.display = '';*/
        var alpha = 0;
        function a() {
            
            alpha++;
            setOpacity(domId, alpha);
            if (alpha < 21) setTimeout(a, 1);
        }	
        setTimeout(a, 5);
    }
}

function RedimensionarIframe(Me) {

    Me.height = 0;
    Me.width = 0;

    var iframeHeight = 0;
    var iframeWidth = 0;
  
    var objDoc = top.frames[Me.id].document;

    if (objDoc != undefined) {
        alert(objDoc);

        iframeHeight = (objDoc.documentElement.scrollHeight ? objDoc.documentElement.scrollHeight : objDoc.body.scrollHeight ? objDoc.body.scrollHeight : objDoc.body.offsetHeight);
        iframeWidth = (objDoc.documentElement.scrollWidth ? objDoc.documentElement.scrollWidth : objDoc.body.scrollWidth ? objDoc.body.scrollWidth : objDoc.body.offsetWidth);
        
        if (objDoc.body.offsetHeight) {
            iframeHeight = objDoc.body.offsetHeight;

        }

        var oParentDiv = document.getElementById('ModalCentral');

        if (oParentDiv) {
            alert(iframeHeight);
            oParentDiv.style.height = 0;
            oParentDiv.style.height = iframeHeight;
            oParentDiv.style.width = 0;
            oParentDiv.style.width = iframeWidth;
            oParentDiv.style.position = 'absolute';
            oParentDiv.style.top = '50%';
            oParentDiv.style.left = '50%';
            oParentDiv.style.marginLeft = '-' + (iframeWidth / 2) + 'px';
            oParentDiv.style.marginTop = '-' + (iframeHeight / 2) + 'px';
        }          
        	
        
        Me.height = iframeHeight;
        Me.width = iframeWidth;
     
    }

}

/*Elimina todos los tags html de una cadena*/
function RemoveHTMLTags(cadena) {
    return cadena.replace(/(<([^>]+)>)/ig, "");
}

/*Para evitar request form peligroso en post de form cuando se introduce codigo html en un textbox por ejemplo*/
function EncodeHTMLForPost(cadena) {

    var value;

    value = cadena;
    
    value = value.replace(/</g, "&lt;");
    value = value.replace(/>/g, "&gt;");    
    value = value.replace("script", "");

        return value;

}

function DecodeHTMLFromPost(cadena) {

    var value;

    value = cadena;
    
    value = value.replace(/&lt;/g, "<");
    value = value.replace(/&gt;/g, ">");
    value = value.replace("script", "");

    return value;

}

/*
var lastColorUsed;

function changeBackColor(row, highlight, color) {
if (highlight) {
lastColorUsed = row.style.backgroundColor;
row.style.backgroundColor = color;
} else {
row.style.backgroundColor = lastColorUsed;
}
}
*/

//Redimensionamiento de iFrame
function autoResizeiFrame(obj) {
    var newheight;
    var newwidth;
    var objDoc;

    if (top.frames[obj.id]) {

        objDoc = top.frames[obj.id].document;       

    }
    else if(window.frames[obj.id]){
    
         objDoc = window.frames[obj.id].document;
    }
    
     if (objDoc) {

            newheight = (objDoc.documentElement.scrollHeight ? objDoc.documentElement.scrollHeight : objDoc.body.scrollHeight ? objDoc.body.scrollHeight : objDoc.body.offsetHeight);
            newwidth = (objDoc.documentElement.scrollWidth ? objDoc.documentElement.scrollWidth : objDoc.body.scrollWidth ? objDoc.body.scrollWidth : objDoc.body.offsetWidth);
            obj.height = (newheight) + "px";
            obj.width = (newwidth) + "px";
            
        }
    
   
}
//función que asigna al src de un iframe el valor de un hiddenvalue. Hay que llamar a esta función pasandole como segundo parametro asi: '<%= myhiddenField.clientID %>'
function iframeSetSrcFromServerHiddenField(iframeId, hiddenFieldId) {

        var ifr = document.getElementById(iframeId);

    if (ifr) {

        var hd = document.getElementById(hiddenFieldId);

        if (hd) {
            ifr.src = hd.value;
        }

    }
}

//Función que asigna a un iframe una url en src
function iframeSetSrc(iframeId, url) {

    var ifr = document.getElementById(iframeId);

    if (ifr) {
               
            ifr.src = url;        

    }
}

// filesystem based script resource
function identityFunction(arg) {
    return arg;
}

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
