(function() {
	var Dom = YAHOO.util.Dom;
	var Event = YAHOO.util.Event;
	var DDM = YAHOO.util.DragDropMgr;

	var parseList = function(col) {
		var items = col.childNodes;
		var positions = new Array(); 
		for (i=0;i<items.length;i++) {
			if(items[i].id != "")
				positions[i]= items[i].id;
		}
		return positions;
	}; 

	YAHOO.example.DDApp = {
			init: function() {
		var rows=6,cols=2,i,j;
		for (i=1;i<cols+1;i=i+1) {
			new YAHOO.util.DDTarget("col"+i);
		}

		for (i=1;i<cols+1;i=i+1) {
			for (j=1;j<rows+1;j=j+1) {
				new YAHOO.example.DDList("row" + i + "_" + j);
			}
		}

	}
	};


//	custom drag and drop implementation


	YAHOO.example.DDList = function(id, sGroup, config) {

		YAHOO.example.DDList.superclass.constructor.call(this, id, sGroup, config);

		this.logger = this.logger || YAHOO;
		var el = this.getDragEl();
		Dom.setStyle(el, "opacity", 0.30); // The proxy is slightly transparent

		this.goingUp = false;
		this.lastY = 0;
	};

	YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, {

		startDrag: function(x, y) {
		this.logger.log(this.id + " startDrag");

		// make the proxy look like the source element
		var dragEl = this.getDragEl();
		var clickEl = this.getEl();
		Dom.setStyle(clickEl, "visibility", "hidden");

		dragEl.innerHTML = clickEl.innerHTML;
		dragEl.className = clickEl.className; 
	},

	endDrag: function(e) {
		var srcEl = this.getEl();
		var proxy = this.getDragEl();

		// Show the proxy element and animate it to the src element's location
		Dom.setStyle(proxy, "visibility", "");
		var a = new YAHOO.util.Motion( 
				proxy, { 
					points: { 
					to: Dom.getXY(srcEl)
				}
				}, 
				0.2, 
				YAHOO.util.Easing.easeOut 
		);
		var proxyid = proxy.id;
		var thisid = this.id;

		// Hide the proxy and show the source element when finished with the animation
		a.onComplete.subscribe(function() {
			Dom.get(proxyid).innerHTML = "<!--Castci ama a Tativel-->";    
			Dom.setStyle(proxyid, "visibility", "hidden");
			Dom.setStyle(thisid, "visibility", "");
		});
		a.animate();
		var col1 = Dom.get("col1");
		var col2 = Dom.get("col2");
		var posicionesCol1 = parseList(col1);
		var posicionesCol2 = parseList(col2);
		YAHOO.util.Cookie.setSub("home","posicionesColumna1", posicionesCol1);
		YAHOO.util.Cookie.setSub("home","posicionesColumna2", posicionesCol2);
	},

	onDragDrop: function(e, id) {

		// If there is one drop interaction, the li was dropped either on the list,
		// or it was dropped on the current location of the source element.
		if (DDM.interactionInfo.drop.length === 1) {

			// The position of the cursor at the time of the drop (YAHOO.util.Point)
			var pt = DDM.interactionInfo.point; 

			// The region occupied by the source element at the time of the drop
			var region = DDM.interactionInfo.sourceRegion; 

			// Check to see if we are over the source element's location.  We will
			// append to the bottom of the list once we are sure it was a drop in
			// the negative space (the area of the list without any list items)
			if (!region.intersect(pt)) {
				var destEl = Dom.get(id);
				var destDD = DDM.getDDById(id);
				destEl.appendChild(this.getEl());
				destDD.isEmpty = false;
				DDM.refreshCache();
			}

		}
	},

	onDrag: function(e) {

		// Keep track of the direction of the drag for use during onDragOver
		var y = Event.getPageY(e);

		if (y < this.lastY) {
			this.goingUp = true;
		} else if (y > this.lastY) {
			this.goingUp = false;
		}

		this.lastY = y;
	},

	onDragOver: function(e, id) {

		var srcEl = this.getEl();
		var destEl = Dom.get(id);

		// We are only concerned with list items, we ignore the dragover
		// notifications for the list.
		if (destEl.nodeName.toLowerCase() == "div") {
			var orig_p = srcEl.parentNode;
			var p = destEl.parentNode;

			if (this.goingUp) {
				p.insertBefore(srcEl, destEl); // insert above
			} else {
				p.insertBefore(srcEl, destEl.nextSibling); // insert below
			}
			DDM.refreshCache();
		}
	}
	});
})();




//xmlhttpObject y cosas para las encuestas


var url = {
		encuestas:{relLink:"encuestas/control.php", elId:"polls"},
		votaEncuesta:{relLink:"encuestas/procesaVoto.php", elId:"polls"},
		reporteros:{relLink:"Reporteros/topNoticiaReportero.php", elId:"reporteros"}
};

reporteros = {
		top:{relLink:"Reporteros/topNoticiaReportero.php", elId:"reporteros"}
};


var elId;
var elIdReporteros;

YAHOO.util.Event.on("enviarImg", "click", votar, url.votaEncuesta);
YAHOO.util.Event.on("liveStream", "click", openStream, null);
YAHOO.util.Event.on("webCam", "click", openVideo, null);
YAHOO.util.Event.on("rumble", "click", popupRamble, null);

function openStream() {
	
window.open('http://noticiasmvs.com/mvsPlayer/container.php?var=noticiasMVS','popup','width=330,height=250,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0');
	//return false;
}

//function openVideo() {
//	window.open('http://apmediastr.triara.com/mvs','webCam','width=640,height=480,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0');
//}
function openVideo() {
	window.open('WebCam.php','webCam','width=640, height=480, scrollbars=no, resizable=no, toolbar=no, directories=no, location=no, menubar=no, status=no, left=0, top=0');
}


function popupRamble () {
        
window.open('http://noticiasmvs.com/popupRamble.htm','popupRamble','width=430,height=430,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0');
//return false;
}




/**
 * Initializes xmlhttp object
 * 
 * @return XMLHTTP request object
 */
function getXmlHttpObject() {
	var requestVar = null;

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		requestVar = new XMLHttpRequest();
	}

	if (window.ActiveXObject) {
		// code for IE6, IE5
		requestVar = new ActiveXObject("Microsoft.XMLHTTP");
	}

	return requestVar;
}


/**
 * Adds a browse element to the previously specified hmtl element
 * 
 * @return undefined
 */
function getGenericResponse() {
	//alert(xmlhttp.readyState);

	if(xmlhttp.readyState == 4) {
		document.getElementById(elId).innerHTML = xmlhttp.responseText;
	}
}


/**
* Sends vote to server to be processed
*/
function votar(jsonList) {

	// Asignamos el valor del radio:

		var myArray = document.getElementsByName("radioVotacion");
var parametros;


for (i=0; i < myArray.length; i++) {
	if (myArray[i].checked) {
		parametros = myArray[i].value;
	}
}

if(parametros != undefined && parametros != '' && parametros != null) {
	xmlhttp = getXmlHttpObject();
	if(xmlhttp == null) {
		alert("Your browser does not support AJAX!");
		return;
	}

	// El archivo que procesa la info
	var urlRel = 'encuestas/procesaVoto.php';


	// la cadena que va a ser procesada
	var params = "seleccion=" + parametros + "&sid=" + Math.random();


	// Posteamos la informacion
	xmlhttp.open("POST", urlRel, true);

	// Cuando se ha ejecutado un cambio de estado
	elId = 'polls';
	xmlhttp.onreadystatechange = getGenericResponse;

	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type",   "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection",     "close");

	xmlhttp.send(params);
}
else {
	alert('Debe seleccionar una respuesta');
}
}

/**
* Posts a request to a .php file and returns the processed information
* 
* @param str:String
* @return
*/
function enviarRecibir(jsonList) {

	xmlhttp = getXmlHttpObject();
	if(xmlhttp == null) {
		alert("Your browser does not support AJAX!");
		return;
	}

	// El archivo que procesa la info
	var urlRel = jsonList.relLink;

	// la cadena que va a ser procesada
	var params = "q=1" + "&sid=" + Math.random();


	// Posteamos la informacion
	xmlhttp.open("POST", urlRel, true);

	// Cuando se ha ejecutado un cambio de estado
	elId = jsonList.elId;
	xmlhttp.onreadystatechange = getGenericResponse;

	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type",   "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection",     "close");

	xmlhttp.send(params);



}


/**
* Adds a browse element to the previously specified hmtl element
* 
* @return undefined
*/
function getSeccionReporteros() {
	//alert(xmlhttp.readyState);
	if(xmlhttp.readyState == 4) {
		document.getElementById(elIdReporteros).innerHTML = xmlhttp.responseText;
	}
}

//////////////////////////////////////////////////////////////////////////////
//mecanismo para hacer fadeout-fadein del encabezado

function fadeObject(id, c1, c2, s1, s2) {
	var self = this;
	this.id      = id;
	this.elem    = false;
	this.colour  = {
			stt: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)],
			end: [parseInt(c2.substr(0, 2), 16), parseInt(c2.substr(2, 2), 16), parseInt(c2.substr(4, 2), 16)],
			now: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)]
	};
	this.steps   = [s1, s2];
	this.dir     = false;
	this.active  = false;
	this.queue   = [];
	this.msg     = [];
	this.message = 0;
	function d2h(num) {
		num = Math.round(num);
		return ((num < 16) ? "0" : "") + num.toString(16);
	}
	this.fade = function(message, direction) {
		this.elem = this.elem || document.getElementById(this.id);
		this.queue.push([message, direction]);
		for (var x = 0; x < this.queue.length; x++) {
			for (var y = x + 1; y < this.queue.length; y++) {
				if (this.queue[x][0] == this.queue[y][0] && this.queue[x][1] != this.queue[y][1]) {
					this.queue.splice(x, 1);
					this.queue.splice(y - 1, 1);
				}
			}
		}
		if (!this.active) setTimeout(function() { self.fadeLoop(); }, 10);
	};
	this.fadeLoop = function() {
		if (!this.active && this.queue.length) {
			if (this.dir && this.message != this.queue[0][0]) this.queue.unshift([this.message, false]);
			var msg = this.queue.shift();
			if (this.msg[msg[0]]) {
				this.active = true;
				this.elem.innerHTML = this.msg[this.message = msg[0]];
				this.dir = msg[1];
			}
		}
		if (this.dir) {
			var c1 = this.colour.stt, c2 = this.colour.end, s = this.steps[0];
		} else var c1 = this.colour.end, c2 = this.colour.stt, s = this.steps[1];
		for (var x = 0, cnow = "", inc = 0; x < 3; x++) {
			this.colour.now[x] += inc = (c2[x] - c1[x]) / s;
			cnow += this.colour.now[x] = (inc < 0) ? Math.max(this.colour.now[x], c2[x]) : Math.min(this.colour.now[x], c2[x]);
		} this.elem.style.color = "#" + d2h(this.colour.now[0]) + d2h(this.colour.now[1]) + d2h(this.colour.now[2]);
		if (cnow == c2.join("")) {
			this.active = false;
			if (!this.queue.length) {
				if (!this.dir) {
					if (this.msg[0]) {
						this.queue.push([0, true]);
						setTimeout(function() { self.fadeLoop(); }, 10);
					} else this.elem.innerHTML = "&nbsp;";
				}
			} else setTimeout(function() { self.fadeLoop(); }, 10);
		} else setTimeout(function() { self.fadeLoop(); }, 10);
	};
	if (window.addEventListener) {
		window.addEventListener('load', function() { self.fade(0, true); }, false); 
	} else if (window.attachEvent)
		window.attachEvent('onload', function() { self.fade(0, true); });
}

//////////////////////////////////////////////////////////////////////////////
//mecanismo para reloj tomado del drupal de mvsradio

var RelojID12 = null 
var RelojEjecutandose12 = false  

function DetenerReloj12 () {  
	if(RelojEjecutandose12)  
		clearTimeout(RelojID12)  
		RelojEjecutandose12 = false  
}  

function MostrarHora12 () {  
	var nombres_dias  = new Array("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado");  
	var nombres_meses = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
	var ahora = new Date();  
	var horas = ahora.getHours();
	var minutos = ahora.getMinutes();  
	var segundos = ahora.getSeconds();  
	var dia_mes = ahora.getDate();
	var dia_semana = ahora.getDay();
	var mes = ahora.getMonth() + 1;  
	var anio = ahora.getFullYear();  


	var meridiano;  

	//ajusta las horas  
	if (horas > 12) {  
		horas -= 12;  
		meridiano = " P.M.";  
	} else {  
		meridiano = " A.M.";  
	}  

	//establece las horas  
	if (horas < 10)  
		ValorHora = "0" + horas;  
	else  
		ValorHora = "" + horas;  

	//establece los minutos  
	if (minutos < 10)  
		ValorHora += ":0" + minutos;  
	else  
		ValorHora += ":" + minutos;  

	//establece los segundos  
	if (segundos < 10)  
		ValorHora += ":0" + segundos;  
	else  
		ValorHora += ":" + segundos;  

	ValorHora += meridiano;  
	document.reloj12.digitos.value = nombres_meses[mes - 1] + " " + dia_mes + ", " + anio + " - " + ValorHora;  

	//si se desea tener el reloj en la barra de estado, reemplazar la anterior por esta  
	//window.status = ValorHora  

	RelojID12 = setTimeout("MostrarHora12()",1000)  
	RelojEjecutandose12 = true  
}  

function IniciarReloj12 () {  
	DetenerReloj12();  
	MostrarHora12();  
}

if (document.captureEvents) {
	document.captureEvents(Event.LOAD);  
}  

/*
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf( "safari" ) != -1 ) {
	var styles = 'http://radio.mvsdigital.com.mx/sites/all/themes/mvsTheme/style.webkit.css';

	var newSS=document.createElement('link');
	newSS.rel='stylesheet';
	newSS.type='text/css';
	newSS.media='all';
	newSS.href= styles;
	document.getElementsByTagName("head")[0].appendChild(newSS);
}
*/

//botón de facebook

function fbs_click() 
{
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=586,height=306');
	return false;
}	


///////////////////////////////////////////////////////////////////////////
//función  que elimina todos los elemmentos del playlist.
///////////////////////////////////////////////////////////////////////////
function deleteAllPlayList(){
	var playlist = YAHOO.util.Dom.get("contenedorRolas");
	var primero = YAHOO.util.Dom.getFirstChildBy(playlist);
	while(primero != null){
		YAHOO.util.Dom.setStyle(primero,'display','none');
		var hermano = YAHOO.util.Dom.getNextSibling(primero);
		primero = hermano;
	};
}


///////////////////////////////////////////////////////////////////////////
//función para emailear el link a un amigo.
///////////////////////////////////////////////////////////////////////////
function mailpage()
{
	mail_str = "mailto:?subject=Revisa la p"+String.fromCharCode(225)+"gina de " + document.title;
	mail_str += "&body=Creo que puede interesarte la nota de " + document.title;
	mail_str += ". La puedes ver en, " + location.href;
	location.href = mail_str;
}

///////////////////////////////////////////////////////////////////////////////
//Función que manda la busqueda del audio a la página correspondiente
///////////////////////////////////////////////////////////////////////////////
function buscaAudio(e){
	var audioBox = YAHOO.util.Dom.get("encuentraAudioBox");
	if(audioBox.value == "" || audioBox.value == "Encuentra tu audioentrevista" || audioBox.value == "Introduzca su parametro de b�squeda"){
		audioBox.value = "Introduzca su parametro de b�squeda";
	}else{	
		window.location.href="entrevistas.php?keyword="+audioBox.value;
	}
}

///////////////////////////////////////////////////////////////////////////////
//Función que manda la busqueda del audio a la página correspondiente
///////////////////////////////////////////////////////////////////////////////
function buscaEnMVS(e){
	var buscaBox = YAHOO.util.Dom.get("buscaMVSBox");
	if(buscaBox.value == "" || buscaBox.value == "Buscar en MVS" || buscaBox.value == "Introduzca su parametro de b�squeda"){
		buscaBox.value = "Introduzca su parametro de b�squeda";
	}else{	
		window.location.href="resultadoBusqueda.php?keyword="+buscaBox.value;
	}
}

/////////////////////////////////////////////////////////////////////
// Menu Drop Down Del Yui para Noticias
/////////////////////////////////////////////////////////////////////
/*
Initialize and render the MenuBar when its elements are ready 
to be scripted.
*/
	YAHOO.util.Event.onContentReady("ddmenu", function () {

/*
	Instantiate a MenuBar:  The first argument passed to the constructor
	is the id for the Menu element to be created, the second is an 
	object literal of configuration properties.
*/
		var oMenuBar = new YAHOO.widget.MenuBar("ddmenu", { 
                                           autosubmenudisplay: true, 
                                           hidedelay: 1500, 
                                           lazyload: true 
                                           }
		);

/*
    Call the "render" method with no arguments since the 
    markup for this MenuBar instance is already exists in 
    the page.
*/
oMenuBar.render();
		}
	);

//////////////////////////////////////////////////////////////////////////
////Función que obtiene la posiciòn de los mòdulos para dibujarlos en el 
////en el caso de que existan cookies
/////////////////////////////////////////////////////////////////////////
var acomodador = {
	buscaCookies:function(){
		if(YAHOO.util.Cookie.get("home")!= null){
			var col1 = YAHOO.util.Cookie.getSub("home", "posicionesColumna1").split(",");
			var col2 = YAHOO.util.Cookie.getSub("home", "posicionesColumna2").split(",");
			columna1 = document.getElementById("col1");
			columna2 = document.getElementById("col2");
			var i = 0;
			for(i=0;i<col1.length;i++){
				if(col1[i] != ""){
					columna1.appendChild(document.getElementById(col1[i]));
				}
			}
			for(i=0;i<col1.length;i++){
				if(col2[i] != "")
					columna2.appendChild(document.getElementById(col2[i]));
			}
		}
	}
};

