var listid = '';
var msie = checkIt('msie') > 0;
var opera = checkIt('opera') > 0;
var mozilla = checkIt('mozilla') > 0;
var sURL = new String(document.location.href);
var idprg = '';
var paramsPopUp = 'dependent=1,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,';
var paramsPopUpScroll = 'dependent=1,toolbar=0,location=0,status=0,menubar=0,scrollbars=1,resizable=0,';
var paramsStd = 'dependent=0,toolbar=1,location=1,status=1,menubar=1,scrollbars=1,resizable=1,';


function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
	   if (!clip) return;
	   
	   // create a transferable
	   var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
	   if (!trans) return;
	   
	   // specify the data we wish to handle. Plaintext in this case.
	   trans.addDataFlavor('text/unicode');
	   
	   // To get the data from the transferable we need two new objects
	   var str = new Object();
	   var len = new Object();
	   
	   var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
	   
	   var copytext=meintext;
	   
	   str.data=copytext;
	   
	   trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);
	   
	   var clipid=Components.interfaces.nsIClipboard;
	   
	   if (!clip) return false;
	   
	   clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
	alert('\xA1 LISTO ! \n \n El pin ha sido copiado al portapapeles. Para pegarlo puede hacerlo presionando Ctrl + V de su teclado');
}


function openpramer(){
    openW('http://www.pramer.tv/', 800, 600, paramsStd, 'pramer');
}

function download(url){
    openW(url, 400, 400, paramsPopUpScroll, 'descarga');
}

function downloadimage(url, fid){
    openW('getFile.aspx?md=img&file='+url+'&oid='+fid, 400, 400, paramsPopUp, 'descarga');
}

function downloadfile(url, othername, fid){
    path = self.location = 'getFile.aspx?md=file&rname='+othername+'&file='+url+'&oid='+fid;
    $('dwnarea').innerHTML = '<iframe src="'+path+'"></iframe>';
    //self.location = 'getFile.aspx?md=file&rname='+othername+'&file='+url;
    //openW('getFile.aspx?md=file&rname='+othername+'&file='+url, 10, 10, paramsPopUpScroll, 'descarga');
}

function findcontrol(partialname){
    var sx = $$('[id*='+partialname+']');
    if (sx.length>0){
        return sx[0];
    } else {
        return null;
    }
}

function openW(url,wd, hg, params, id){
     window.open(url, 'wnd000'+id, params + 'width='+wd+',height='+hg)

}

function checkIt(string)
{
    var detect = navigator.userAgent.toLowerCase();
	place = detect.indexOf(string) + 1;
	return place;
}


function getURLParameters() 
{
	//var sURL = new string(document.location).toLowerCase();
	//var sURL = document.location.toString();
	
	if (sURL.indexOf("?") > 0)
	{
		var arrParams = sURL.split("?");
			
		var arrURLParams = arrParams[1].split("&");
		
		arrParamNames = new Array(arrURLParams.length);
		arrParamValues = new Array(arrURLParams.length);
		
		var i = 0;
		for (i=0;i<arrURLParams.length;i++)
		{
			var sParam =  arrURLParams[i].split("=");
			arrParamNames[i] = sParam[0];
			if (sParam[1] != "")
				arrParamValues[i] = unescape(sParam[1]);
			else
				arrParamValues[i] = "";
		}
		alen = 1;
	} else {
		alen = 0;
	}
}

function getparam(param){
	var res = "";
	var i = 0;
	if (alen != 0) {
		for (i=0;i<arrParamNames.length;i++){
			if (arrParamNames[i]==param){
				res = arrParamValues[i];
			}
		}	
	} 
	return res;
}

function initPage(){
    getURLParameters();
    //Funciones para listado de programas y busqueda    
    var ctrl = findcontrol('lstBoxPrograms');
    if (ctrl!=null){
        //Buscamos el componente para ver si estamos en la pagina correcta
        //Si encontramos el control del listado, inicializamos el resto
        //Primero, guardamos el id que nos devuelve
       listid = ctrl.id;
       //Llamamos ala funcion para crear los divs
       listpopulate();
       //Asignamos al campo de texto la propiedad para que en el KeyUp se actualize la caja de busqueda
       Event.observe('txtBusca', 'keyup', filterProg);    
    }    
    //Revisamos sinestamos en contacto
    ctrl = findcontrol('lbPrograms');
    if (ctrl!=null){
        if ($('combocell') != null) {
            listid = ctrl.id;
            if (findcontrol('proID').value!=''){
                idprg = findcontrol('proID').value;
            } 
            if (idprg==''){
                if (getparam('ID')!=''){
                    idprg = getparam('ID');
                }        
            }
            createcomboprog();
            $('combocell').observe('click', showHideCombo);
        }
    }    
}


function createcomboprog(){
    var container  = document.createElement('DIV');
    container.id = 'comboprog';
    container.className = 'hidelist';
    $('contactTable').appendChild(container);            
    for (t=0; t<$(listid).length; t++){        
		var objid = $(listid).options[t].value;
		if (objid!=''){
		    var nwdv  = document.createElement('DIV');
            nwdv.id = objid;
            nwdv.innerHTML = $(listid).options[t].text;
            nwdv.className = "itemOff";         
            $('comboprog').appendChild(nwdv);            
		    $(objid).observe('mouseover', setclassOn);
		    $(objid).observe('mouseout', setclassOff);
		    $(objid).observe('click', selectProgram);
		    if (objid==idprg){		    
                $('combocell').innerHTML = $(listid).options[t].text;
                findcontrol('proID').value = $(listid).options[t].value;		        
		    }
		}
    }
}

function showHideCombo(){
    //Muestra/Oculta el combo
    //Buscamos posicion    
    if ($('comboprog').className == 'listacombo'){
        $('comboprog').className = 'hidelist';
    } else {
        var psx = new PositionOnScreen('combocell');
        psx.getPos();
        var top = psx.y;
        var left = psx.x;
        var off = getOffset();
        if (off>0){
            top = top + off;
        }
        $('comboprog').className = 'listacombo';
        $('comboprog').style.top = (top + 24) + 'px';
        $('comboprog').style.left = (left - 3) + 'px';
    }
}

function selectProgram(el){    
    $('combocell').innerHTML = Event.element(el).innerHTML;
    findcontrol('proID').value = Event.element(el).id;
    showHideCombo();    
}

function listpopulate(){
    //Creamos la lista de programas en base al Listbox oculto.
    for (t=0; t<$(listid).length; t++){
        //Creamos elemento
        nwdv  = document.createElement('DIV');
		var objid = $(listid).options[t].value;
		//Definimos ID y propiedades
        nwdv.id = objid;
        nwdv.innerHTML = $(listid).options[t].text;
        nwdv.className = "itemOff";         
        /*lnk  = document.createElement('A');
        lnk.href = "FichaPrograma.aspx?ID=" + objid;
        lnk.innerText = $(listid).options[t].text;
        lnk.className = 'clsClr';
        nwdv.appendChild(lnk);*/
        //Lo agregamos al contenedor       
        $('lista0').appendChild(nwdv);
        //Definimos los eventos para que cambie de color y que haga click
		$(objid).observe('mouseover', setclassOn);
		$(objid).observe('mouseout', setclassOff);
		$(objid).observe('click', dispathPage);
    }
}

function dispathPage(el){
    self.location = 'FichaPrograma.aspx?ID=' + Event.element(el).id;
}

function setclassOn(el){   
    //Cambiamos el estilo del item que genero el evento     
 	Event.element(el).className = 'itemOn';
}
function setclassOff(el){
 	Event.element(el).className = 'itemOff';
}
function filterProg(){
    //Obtenemos el valor del filtro
    var txt = $('txtBusca').value;    
    for (t=0; t<$(listid).length; t++){
        itmid = $(listid).options[t].value;
        var itm = $(listid).options[t].text.toLowerCase();
        if (txt==''){
            //Si el texto esta vacio encendemos todos
            $(itmid).style.display = 'block';
        } else {
            //Si buscamos un texto, encendemos o apagamos
            //en abse a si contiene o no el texto
            if (itm.indexOf(txt)==-1){
                $(itmid).style.display = 'none';
            } else {
                $(itmid).style.display = 'block';                
            }
        }
    }
}

function StopCaptcha(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13) && (node.type=="text")) {
		Validar = $$('[id*=Ingresar]');
		$(Validar[0].id).click();
		return false;
	}
}

function Formulario(elValor) {
    findcontrol('Formulario').value = elValor;
}

function FormularioFocus() {
  try {
    Resultado = $$('[id*=txtName]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('1'); });
    Resultado = $$('[id*=txtLastName]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('1'); });
    Resultado = $$('[id*=txtMail]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('1'); });
    Resultado = $$('[id*=txtPassw]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('1'); });
    Resultado = $$('[id*=txtPassEq]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('1'); });
    Resultado = $$('[id*=txtIMail]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('2'); });
    Resultado = $$('[id*=txtiPass]'); Resultado = $(Resultado[0].id).observe('focus', function (event) { Formulario('2'); });
	} catch(err) {
    Resultado = 0;
	}
}

function stopRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    var Validar;
	if ((evt.keyCode == 13))
	{
        if ((findcontrol('Formulario').value) == '1') {
            Validar = $$('[id*=btnRegisterme]');
            $(Validar[0].id).click();
            return false;                    
        } else {
            Validar = $$('[id*=btnLogin]');
            $(Validar[0].id).click();
            return false;
        }
    }
}
//Fin programacion


//En el onload llamamos esta funcion
Event.observe(window, 'load', initPage);