// JavaScript Document

var G_LOADED = false;
var acc = 0;
//var z = myrandom(7) - 1;
var colores = new Array("#d8d8ff", "#ffffd8", "#d8ffd8", "#e7d8ef", "#ffe7d8", "#d8d8d8", "#efe7d8");


function XBw(ly){
	var nw = document.getElementById ? document.getElementById(ly):document.layers? document.layers[ly]: document.all? document.all[ly]:null;
	return nw;
} 


function OpenRep(arch){
	window.open(arch,"SAU20");
}


function myrandom(ax){
	var rnd = new Object();
	rnd.today=new Date();
	rnd.seed=rnd.today.getTime();

	rnd.seed = (rnd.seed*9301+49297) % 233280;
	var seed = rnd.seed/(233280.0);

	return Math.ceil(seed*ax);
}


function ChangeC(){
	//clearTimeout(st);
	var capas = new Array( "menu", "Uni", "Dir", "Mod", "Bib", "Bec", "Riu", "Ate", "aUni",
						  	"aDir", "aMod", "aBib", "aBec", "aRiu", "aAte", "menu", "eventos",
							"ev", "nota", "liga", "fd", "servicios", "promos", "fecha",
							"loc", "ndia", "fdia", "mes", "rj", "aloc", "andia", "afdia",
							"ames", "sfanio", "clima", "aclima", "piesb", "cont", "riuadyi",
							"act", "mex", "usuariosalter", "inst" );
	var lcapas = capas.length;
	
	for ( var i = 0; i < lcapas; i++ ){
		var capa = XBw( capas[i] );
		capa.style.backgroundColor = colores[z];
	}

}		

function muestra( que ){
	
	var w = XBw( que );
	var x = XBw( "a"+que );
	var y = XBw( "s"+que );
	var d = XBw( "ind" );
	
	clearAll();

	switch (que){
		case 'Uni': var pos = 45;  break;
		case 'Dir': var pos = 111; break;
		case 'Mod': var pos = 195; break;
		case 'Bib': var pos = 279; break;
		case 'Bec': var pos = 361; break;
		case 'Riu': var pos = 437; break;
		case 'Ate': var pos = 510; break;
	}
	d.style.left = pos+"px";
	w.style.backgroundColor = colores[z];
	x.style.backgroundColor = colores[z];
	x.style.color = "#663300";
	y.style.visibility = "visible";
	
}

function clearAll(){
	
	var capas = new Array( "Uni", "Dir", "Mod", "Bib", "Bec", "Riu", "Ate" );
	var l = capas.length;
	
	for ( var ui = 0; ui < l; ui++ ){
		var w = XBw( capas[ui] );
		var x = XBw( "a"+capas[ui] );
		var y = XBw( "s"+capas[ui] );

		w.style.backgroundColor = colores[z];
		x.style.backgroundColor = colores[z]
		x.style.color = "#000000";
		y.style.visibility = "hidden";
	}

}


function imprime(){
	var liga = this.location.href;
	var res = liga.slice(19)
	var lst = res.lastIndexOf("/") + 1;
	var r1 = res.slice(0,lst);
	var r2 = res.slice(lst);
	if (r2 == ""){ r2 = "index.html"; }
	switch (r2){
		case "calendario.html":
			this.location.href = "http://www.uady.mx/print.html?pag="+r1+"c_calendariop.html&url="+res;
			break;
		case "postal.html":
			this.location.href = "http://www.uady.mx/print.html?pag="+r1+"c_postalp.html&url="+res;
			break;
		case "ec.html":
		case "escprep.html":
		case "facs.html":
		case "ct.html":
		case "cir.html":
		case "asc.html":
		case "lic.html":
		case "lical.html":
		case "pos.html":
		case "dip.html":
		case "esp.html":
		case "mae.html":
		case "doc.html":
		case "bus.html":
		case "index.html":
		case "clima.html":
			if ((r1 != "directorio/" && r2 == "index.html")){
				this.location.href = "http://www.uady.mx/print.html?pag="+r1+"c_"+r2+"&url="+res;
			}else{
				var scd = r2.lastIndexOf(".");
				var n = r2.slice(0, scd);
				this.location.href = "http://www.uady.mx/print.html?pag="+n+"&url="+res;
			}
			break;
		case "avanzado.html":
			var n =	document.srvs.que.value;
			this.location.href = "http://www.uady.mx/print.html?pag=avanzado:"+n+"&url="+res;
			break;
		default:
			this.location.href = "http://www.uady.mx/print.html?pag="+r1+"c_"+r2+"&url="+res;
			break;
	}
}


//funcion para cambiar el tamaño de texto de los contenidos en las plantillas.
function changeTxt( tam ){
	var atam = new Array( "small", "medium", "big", "xbig" );
	
	var x = XBw( "contenido" );
	var y = XBw( "titulo" );

	var galleta = LeerCookie("tg");
	if ( galleta == null || isNaN(galleta)){
		galleta = "1";
	}
	
	tg = parseInt( galleta, 10 );	

	
	if ( tam == "down" ){
		tg--;
		if (tg == -1 ){ tg = 0; }
	}
	
	if ( tam == "up" ){
		tg++;
		if ( tg == 4 ){ tg = 3; }
	}
	
	if ( tam == "reset"){
		tg = 1;
	}
	x.className = atam[tg];
	y.className = atam[tg];
	document.cookie = "tg="+tg;
	
}


function strFix( aq ){
	
	var r;
	
	var a1 = /á/g
	var a2 = /Á/g
	var e1 = /[é]/g
	var e2 = /[É]/g
	var i1 = /[í]/g
	var i2 = /[Í]/g
	var o1 = /[ó]/g
	var o2 = /[Ó]/g
	var u1 = /[ú]/g
	var u2 = /[Ú]/g
	var um1 = /[ü]/g
	var um2 = /[Ü]/g
	var nie1 = /[ñ]/g
	var nie2 = /[Ñ]/g
	
	r = aq.replace( a1, "%E1" );
	r = r.replace( a2, "%C1" );
	r = r.replace( e1, "%E9" );
	r = r.replace( e2, "%C9" );
	r = r.replace( i1, "%ED" );
	r = r.replace( i2, "%CD" );
	r = r.replace( o1, "%F3" );
	r = r.replace( o2, "%D1" );
	r = r.replace( u1, "%FA" );
	r = r.replace( u2, "%DA" );
	r = r.replace( um1, "%FC" );
	r = r.replace( um2, "%DC" );
	r = r.replace( nie1, "%F1" );
	r = r.replace( nie2, "%D1" );

	return r;
}

function envia(as){
	var at = strFix( as );
	alert(at);
	var liga = this.location.href;
	var res = liga.slice(19)
	var lst = res.lastIndexOf("/") + 1;
	var r1 = res.slice(0,lst);
	var r2 = res.slice(lst);
	if (r2 == ""){ r2 = "index.html"; }
	switch (r2){
		case "calendario.html":
			ventanae =	window.open("http://www.uady.mx/email.html?tit="+at+"&pag="+r1+"c_calendariop.html&url="+res,"Email","scrollbars=No,width=500,height=500");
			break;
		case "postal.html":
			ventanae =	window.open("http://www.uady.mx/email.html?tit="+at+"&pag="+r1+"c_postalp.html&url="+res,"Email","scrollbars=No,width=500,height=500");
			break;
		case "ec.html":
		case "escprep.html":
		case "facs.html":
		case "ct.html":
		case "cir.html":
		case "asc.html":
		case "lic.html":
		case "lical.html":
		case "pos.html":
		case "dip.html":
		case "esp.html":
		case "mae.html":
		case "doc.html":
		case "bus.html":
		case "index.html":
		case "clima.html":
			if ((r1 != "directorio/" && r2 == "index.html")){
				ventanae =	window.open("http://www.uady.mx/email.html?tit="+at+"&pag="+r1+"c_"+r2+"&url="+res,"Email","scrollbars=No,width=500,height=500");
			}else{
				var scd = r2.lastIndexOf(".");
				var n = r2.slice(0, scd);
				ventanae =	window.open("http://www.uady.mx/email.html?tit="+at+"&pag="+n+"&url="+res,"Email","scrollbars=No,width=500,height=500");
			}
			break;
		case "avanzado.html":
			var n =	document.srvs.que.value;
			ventanae =	window.open("http://www.uady.mx/email.html?tit="+at+"&pag=avanzado:"+n+"&url="+res,"Email","scrollbars=No,width=500,height=500");
			break;
		default:
			ventanae =	window.open("http://www.uady.mx/email.html?tit="+at+"&pag="+r1+"c_"+r2+"&url="+res,"Email","scrollbars=No,width=500,height=500");
			break;
	}
}

			
function openMediaSelect(){
	var w = 300;
	var h = 150;
	var LPos = (screen.width) ? (screen.width-w)/2 : 0;
	var TPos = (screen.height) ? (screen.height-h)/2 : 0;
	var Settings = 'width='+w+',height='+h+',top='+TPos+',left='+LPos+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no';
	window.open ("sm.html","Dialogo",Settings);
}


function OpenWin(arch, ancho, alto){
	window.open(arch,"Aviso","scrollbars=0,width="+ancho+",height="+alto);
}

function validar(form){
	if (isEmail2(document.formulario.email.value)){
		return true;
	}else{
		alert("Email Inválido.");
		return false;
	}
}

function isEmail2(who){
	var email=/^[A-Za-z0-9][\w-.]+[A-Za-z0-9]@[A-Za-z0-9]([\w-.]+[A-Za-z0-9]\.)+([A-Za-z]){2,4}$/i;
	return(email.test(who));
}

function getDocHeight(doc) {
	  var docHt = 0, sh, oh;
	  if (doc.height) docHt = doc.height;
	  else if (doc.body) {
		  if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
		  if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
		  if (sh && oh) docHt = Math.max(sh, oh);
	  }
	  return docHt;
}

function setIframeHeight(iframeName) {
	  var iframeWin = window.frames[iframeName];
	  var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
	  if ( iframeEl && iframeWin ) {
		iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous  
		var docHt = getDocHeight(iframeWin.document);
		// need to add to height to be sure it will all show
		if (docHt) iframeEl.style.height = docHt + 30 + "px";
	  }
}

function loadIframe(iframeName, url) {
	 if ( window.frames[iframeName] ) {
		 window.frames[iframeName].location = url;   
		return false;
	} else return true;
}
			
//*********************************************************************//
//  GenerarAviso Script, Realizado por LCC. Victor Menendez Dominguez  //
//      Puedes utilizar el código haciendo referencia al autor         //
// No soy responsable de los daños causados por el uso de este script. //
//*********************************************************************//

function LeerCookie( Valor ){
	var Buscar = Valor + "=";
	if ( document.cookie.length > 0 ){
		var cadena = document.cookie.indexOf(Buscar);
		if ( cadena != -1 ){
			cadena += Buscar.length;
			var fin = document.cookie.indexOf(";",cadena);
			if ( fin == -1 ){ fin = document.cookie.length; }
			return unescape(document.cookie.substring(cadena,fin));
		}
	}
}

function GenerarAviso( pag, configuracion, name ){
	var galleta = LeerCookie("Acceso");
	if ( galleta == null ){
		window.open(pag,name,configuracion);
		document.cookie = "Acceso=S";
	}
}


function initFecha(){
	var x1 = XBw( "ndia" );
	var x3 = XBw( "fdia" );
	var x4 = XBw( "mes" );
	
	x1.innerHTML = "";
	x1.innerHTML = "<a id=\"andia\" href=\"http://www.uady.mx/universidad/calendario.html\">"+fndia+"</a>";
	x3.innerHTML = "";
	x3.innerHTML = "<a id=\"afdia\" href=\"http://www.uady.mx/universidad/calendario.html\">"+ffdia+"</a>";
	x4.innerHTML = "";
	x4.innerHTML = "<a id=\"ames\" href=\"http://www.uady.mx/universidad/calendario.html\">"+fmes+", <span id=\"sfanio\">"+fanio+"</span></a>";
}

function reloj(){
	t[2]++; if (t[2] == 60){ t[2] = 0; t[1]++; if (t[1] == 60){ t[1] = 0; t[0]++; if (t[0] == 24){ t[0] == 0; } } } 
	if (t[0] < 10){ var p1 = '0'+t[0]; }else{ var p1 = t[0]; }		
	if (t[1] < 10){ var p2 = '0'+t[1]; }else{ var p2 = t[1]; }		
	if (t[2] < 10){ var p3 = '0'+t[2]; }else{ var p3 = t[2]; }		
	var cad = p1+':'+p2+':'+p3+",<br />"+th;
	var rj = XBw("rj");
	rj.innerHTML="";
	rj.innerHTML= "<a style=\"color:#666666; background-color:"+colores[z]+";\" href=\"http://www.uady.mx/universidad/calendario.html\">"+cad+"</a>";
	setTimeout( 'reloj()', 1000); 	
}


//**********************************************************************//
//				  AJAX					//
//**********************************************************************//

var gdiv="";
var tiempo = "";
var http_request = false;

function makeRequest(url, div, tiempophp) {
	http_request = false;	
	gdiv = div;
	tiempo = tiempophp;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			//http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert(':( No se puede crear una instancia XMLHTTP');
		return false;
	}
	http_request.onreadystatechange = makeEvents;
	http_request.open('GET', url, true);
	http_request.send(null);

}

function makeEvents() {
	//alert (div);
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			var l_largo = xmldoc.getElementsByTagName('item').length;
			var t ;
			var l;
			var d;
			var c;
			var pd;
			var cad = "";
			var hoy = tiempo;
			var intervalo = (86400*3);
			var nuevo = "";
			
			for ( var li = 0; li < l_largo; li++ ){
				t = xmldoc.getElementsByTagName('item')[li].getElementsByTagName( 'title' )[0].firstChild.nodeValue;
				l = xmldoc.getElementsByTagName('item')[li].getElementsByTagName( 'link' )[0].firstChild.nodeValue;
				d = xmldoc.getElementsByTagName('item')[li].getElementsByTagName( 'description' )[0].firstChild.nodeValue;
				c = d.split(" * ");
				pd = xmldoc.getElementsByTagName('item')[li].getElementsByTagName( 'pubDate' )[0].firstChild.nodeValue;
				if ( gdiv == "ev" ){
					cad += "\t<a class=\"nota_leer\" href=\""+l+"\"><img src=\"imagenes/pagina.jpg\" alt=\"&amp;copy; UADY 2010\" border=\"0\">&nbsp;&nbsp;<span class=\"nota_titulo\">"+t+"</span><br />\r\n"+c[0]+c[1]+"</a><br />\r\n<br />\r\n";
				}else{
					fpub = Date.parse(pd)/1000;					
					nuevo = ((fpub+intervalo) > hoy) ? "imagenes/nuevoicon.gif" : "imagenes/pagina.jpg";// Si todavia es nuevo...
					cad += "\t<a class=\"nota_leer\" href=\""+l+"\"><img src=\""+nuevo+"\" alt=\"&amp;copy; UADY 2010\" border=\"0\">&nbsp;&nbsp;<span class=\"nota_titulo\">"+t+"</span><br />\r\n</a>\r\n<br />\r\n";
				}
			}
			var mult = 20;
			var cap = XBw( gdiv );		
				cap.innerHTML = "";
				cap.innerHTML = cad;
			if ( gdiv == "ev" ){	
				makeRequest( "xml/avisos.xml", "cv", tiempo);
			}
		} else {
			alert('Hubo un problema en la petición.');
		}
	}
}


//**********************************************************************//
//				FLASH					//
//**********************************************************************//


function iFlash( asrc, aw, ah, aatt, apd ){
	document.write( "<object type=\"application/x-shockwave-flash\"" );
	document.write( "data=\""+asrc+"?"+aatt+"\"" );
	document.write( "width=\""+aw+"\" height=\""+ah+"\" name=\"themovie\" id=\"themovie\">" );
	document.write( "<param name=\"movie\" value=\""+asrc+"?"+aatt+"\" />");
	document.write( "<param name=\"wmode\" value=\"transparent\" />");
	document.write( "<a href=\"http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&amp;promoid=BIOX\"><img style=\"border:none; padding-top:"+apd+"em;\" src=\"/imagenes/getflash.gif\" width=\"88\" height=\"31\" alt=\"&copy; Macromedia 2006\" /></a>");
	document.write( "</object>");
}

function iFlash2( asrc, aw, ah ){
        document.write( "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"" );
        document.write( "       width=\""+aw+"\"" );
        document.write( "       height=\""+ah+"\"" );
        document.write( "       id=\"miflash\"" );
        document.write( "       name=\"miflash\">" );
        document.write( "       <param name=\"movie\" value=\""+asrc+"\">" );
        document.write( "       <param name=\"quality\" value=\"high\">" );
	document.write( "	<param name=\"wmode\" value=\"transparent\" />");
        document.write( "       <embed  src=\""+asrc+"\"" );
        document.write( "               quality=\"high\"" );
        document.write( "               type=\"application/x-shockwave-flash\"" );
        document.write( "               width=\""+aw+"\"" );
        document.write( "               height=\""+ah+"\"" );
        document.write( "               name=\"miflash\">" );
        document.write( "       </embed></object>");
}



/* FUNCIONES PARA PORTAL 2009!!" */

// Placeholder para buscador
function activatePlaceholders() {
	var detect = navigator.userAgent.toLowerCase();
	if (detect.indexOf("safari") > 0) return false;
	var inputs = document.getElementsByTagName("input");
	for (var i=0;i<inputs.length;i++) {
	  if (inputs[i].getAttribute("type") == "text") {
	   if (inputs[i].getAttribute("placeholder") && inputs[i].getAttribute("placeholder").length > 0) {
		inputs[i].value = inputs[i].getAttribute("placeholder");
		inputs[i].onclick = function() {
		 if (this.value == this.getAttribute("placeholder")) {
		  this.value = "";
		 }
		 return false;
		}
		inputs[i].onblur = function() {
		 if (this.value.length < 1) {
		  this.value = this.getAttribute("placeholder");
		 }
		}
	   }
	  }
	}
}


function busca(tipo){
	var cad;
	var bi = XBw('bi');
	if (bi.value == "" || bi.value == "Buscar"){
		alert("Debe escribir algún texto de búsqueda");
		bi.value = "";
		bi.focus();
	}
	else{
		if (tipo == 'c'){ // Correos (o usuarios, como se le quiera llamar)
			cad = "http://www.uady.mx/phpdigusr/index.php?start=1&pg=1&search=Buscar...&query=";
		}
		else{ // Uadygoogle :D
			cad = "http://www.uady.mx/buscador.html?cx=011439926932938929758%3Afp0b4uk98k8&cof=FORID%3A11&ie=ISO-8859-1&sa=Buscar&q=";
		}
		window.location = cad + bi.value;	
	}
}
// Funciones para el colchon del pie
function getElementPosition(elemID){
var offsetTrail = document.getElementById(elemID);
var offsetLeft = 0;
var offsetTop = 0;
while (offsetTrail){
offsetLeft += offsetTrail.offsetLeft;
offsetTop += offsetTrail.offsetTop;
offsetTrail = offsetTrail.offsetParent;
}
if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
offsetLeft += document.body.leftMargin;
offsetTop += document.body.topMargin;
}
return {left:offsetLeft,top:offsetTop};
}


function sube_pie(){
	var trepa = 0;
	var alt = altura_ventana();
	while (getElementPosition('ancla2').top <alt){
		document.getElementById("ancla3").style.height = trepa+"px";
		trepa++;
	}
}

function altura_ventana(){
	if (window.innerHeight){
		//navegadores basados en mozilla
		espacio_pagina = window.innerHeight
	}else{
		//Navegadores basados en IExplorer, es que no tengo innerheight
		espacio_pagina = document.body.clientHeight
	}
	return espacio_pagina;
}

var ourInterval;
var origColor = "#00CC00";
var overColor = "#DEDEDE";
var scrollSpeed = 50;
var scrollHeight = 3;

function scrollStart(direction, divID, elementID){
//CHANGE THE BACKGROUND COLOR OF THE TD THE MOUSE IS OVER
//document.getElementById(elementID).style.backgroundColor = overColor;
// REPEATED CALL EITHER scrollUp OR scrollDown
ourInterval = setInterval("scroll"+direction+"('"+divID+"')", scrollSpeed);
}
function scrollEnd(which){
// OUR MOUSE IS OUT, SO RETURN TD TO ORIGINAL COLOR
//document.getElementById(which).style.backgroundColor = origColor;
// STOP CALLING THE SCROLL FUNCTION
clearInterval(ourInterval);
}

function scrollUp(which){
// SET THE SCROLL TOP
document.getElementById(which).scrollTop = document.getElementById(which).scrollTop - scrollHeight;
}
function scrollDown(which){
// SET THE SCROLL TOP
document.getElementById(which).scrollTop = document.getElementById(which).scrollTop + scrollHeight;
}

/******************************** menufade *************************************************/

var hoverColour = "#000";

$(function(){
	$("a.hoverBtn").show("fast", function() {
		$(this).attr("class", "");
	});
	//display the hover div
	$("div.hoverBtn").show("fast", function() {
		//append the background div
		$(this).append("<div></div>");
		
		//get link's size
		var wid = $(this).children("a").width();
		var hei = $(this).children("a").height();
		
		//set div's size
		$(this).width(wid);
		$(this).height(hei);
		$(this).children("div").width(wid);
		$(this).children("div").height(hei);
		
		//on link hover
		$(this).children("a").hover(function(){
			//store initial link colour
			if ($(this).attr("rel") == "") {
				$(this).attr("rel", $(this).css("color"));
			}
			//fade in the background
			$(this).parent().children("div")
				.stop()
				.css({"display": "none", "opacity": "1"})
				.fadeIn("fast");
		},function(){
			//fade out the background
			$(this).parent().children("div")
				.stop()
				.fadeOut("slow");
		});
	});
});

/********************************* easySlider 1.8 modificado pa que funcione *****************/

/*
 * 	Easy Slider 1.8 - jQuery plugin
 *	written by Alen Grakalic (modified by Kyle Florence - kyle.florence@gmail.com)
 *	http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */

/*
 *	markup example for $("#slider").easySlider();
 *
 * 	<div id="slider">
 *		<ul>
 *			<li><img src="images/01.jpg" alt="" /></li>
 *			<li><img src="images/02.jpg" alt="" /></li>
 *			<li><img src="images/03.jpg" alt="" /></li>
 *			<li><img src="images/04.jpg" alt="" /></li>
 *			<li><img src="images/05.jpg" alt="" /></li>
 *		</ul>
 *	</div>
 *
 */

(function($)
{
    $.fn.easySlider = function(options)
    {
        // default configuration properties
        var defaults = {
            prevId:         'prevBtn',
            prevText:       'Anterior',
            nextId:         'nextBtn',
            nextText:       'Siguiente',
            controlsShow:   true,
            controlsBefore: '',
            controlsAfter:  '',
            controlsFade:   true,
            insertAfter:    true,
            firstId:        'firstBtn',
            firstText:      'First',
            firstShow:      false,
            lastId:         'lastBtn',
            lastText:       'Last',
            lastShow:       false,
            vertical:       false,
            speed:          800,
            ease:           'swing',
            auto:           false,
            pause:          2000,
            continuous:     false,
            prevNext:       true,
            numeric:        false,
            numericId:      'controls'
        };

        var options = $.extend(defaults, options);

        this.each(function()
        {
            var obj = $(this);

            // Fix for nested list items
            var ul = obj.children("ul");
            var li = ul.children("li");
            var s = li.length;
            var w = ul.width();
            var h = obj.height();			
						

            var t = 0;
            var ts = s-1;
            var clickable = true;

            // Set obj overflow to hidden
            obj.css("overflow","hidden");

            // Set width/height of list items based on width/height of obj
            li.each(function() {
               if(options.vertical) $(this).height(h);
                else $(this).width(w);
            });

            // Float items to the left
            li.css('float', 'left');

            // Set width/height of ul
            if(options.vertical) ul.height(s*w);
            else ul.width(s*h);

            // Clone elements for continuous scrolling
            if(options.continuous)
            {
                if(options.vertical)
                {
                    ul.prepend(li.filter(":last-child").clone().css("margin-top","-"+ h +"px"));
                    ul.append(li.filter(":nth-child(2)").clone());
                    ul.height((s+1)*h);
                } else {
                    ul.prepend(li.filter(":last-child").clone().css("margin-left","-"+ w +"px"));
                    ul.append(li.filter(":nth-child(2)").clone());
                    ul.width((s+1)*w);
                }
            };

            if(options.controlsShow)
            {
                var html = options.controlsBefore;
                if(options.numeric){
                    html += '<ol id="'+ options.numericId +'"></ol>';
                }
                if(options.firstShow) {
                    html += '<span id="'+ options.firstId +'"><a href="#">'+ options.firstText +'</a></span>';
                }
                if(options.prevNext){
                    html += '<span id="'+ options.prevId +'"><a href="#">'+ options.prevText +'</a></span>';
                    html += '<span id="'+ options.nextId +'"><a href="#">'+ options.nextText +'</a></span>';
                }
                if(options.lastShow) {
                    html += '<span id="'+ options.lastId +'"><a href="#">'+ options.lastText +'</a></span>';
                }
                html += options.controlsAfter;

                if (options.insertAfter) $(obj).after(html);
                else $(obj).before(html);
            };

            if(options.numeric)
            {
                for(var i=0;i<s;i++)
                {
                    $(document.createElement("li"))
                        .attr('id',options.numericId + (i+1))
                        .html('<a rel="'+ i +'" href="#"><span>'+ (i+1) +'</span></a>')
                        .appendTo($("#"+ options.numericId))
                        .click(function(){
                            animate($("a",$(this)).attr('rel'),true);
                            return false;
                        });
                };
            }

            if(options.prevNext)
            {
                $("a","#"+options.nextId).click(function(){
                    animate("next",true); return false;
                });
                $("a","#"+options.prevId).click(function(){
                    animate("prev",true); return false;
                });
                $("a","#"+options.firstId).click(function(){
                    animate("first",true); return false;
                });
                $("a","#"+options.lastId).click(function(){
                    animate("last",true); return false;
                });
            };

            function setCurrent(i)
            {
                i = parseInt(i)+1;
                $("li", "#" + options.numericId).removeClass("current");
                $("li#" + options.numericId + i).addClass("current");
            };

            function adjust()
            {
                if(t>ts) t=0;
                if(t<0) t=ts;
                if(!options.vertical) {
                    ul.css("margin-left",(t*w*-1));
                } else {
                    ul.css("margin-top",(t*h*-1));
                }
                clickable = true;
                if(options.numeric) setCurrent(t);
            };

            function animate(dir,clicked)
            {
                if (clickable)
                {
                    clickable = false;
                    var ot = t;
                    switch(dir)
                    {
                        case "next":
                            t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;
                            break;
                        case "prev":
                            t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
                            break;
                        case "first":
                            t = 0;
                            break;
                        case "last":
                            t = ts;
                            break;
                        default:
                            t = parseInt(dir);
                            break;
                    };

                    var diff = Math.abs(ot-t);
                    var speed = diff*options.speed;
                    if(!options.vertical) {
                        p = (t*w*-1);
                        ul.animate(
                            { marginLeft: p },
                            {
                                queue:false,
                                duration:speed,
                                easing:options.ease,
                                complete:adjust
                            }
                        );
                    } else {
                        p = (t*h*-1);
                        ul.animate(
                            { marginTop: p },
                            {
                                queue:false,
                                duration:speed,
                                easing:options.ease,
                                complete:adjust
                            }
                        );
                    };

                    if(!options.continuous && options.controlsFade)
                    {
                        if(t==0){
                            $("a","#"+options.prevId).fadeOut('slow');
                            $("a","#"+options.firstId).fadeOut('slow');
                        } else if(t==ts){
                            $("a","#"+options.nextId).fadeOut('slow');
                            $("a","#"+options.lastId).fadeOut('slow');
                        } else {
                            $("a","#"+options.prevId).fadeIn('slow');
                            $("a","#"+options.firstId).fadeIn('slow');
                            $("a","#"+options.nextId).fadeIn('slow');
                            $("a","#"+options.lastId).fadeIn('slow');
                        };
                    };

                    if(clicked) clearTimeout(timeout);
                    if(options.auto && dir=="next" && !clicked){;
                        timeout = setTimeout(function(){
                            animate("next",false);
                        },diff*options.speed+options.pause);
                    };

                };
            };
            // init
            var timeout;
            if(options.auto){;
                timeout = setTimeout(function(){
                    animate("next",false);
                },options.pause);
            };

            if(options.numeric) setCurrent(0);

            if(!options.continuous && options.controlsFade){
                $("a","#"+options.prevId).hide();
                $("a","#"+options.firstId).hide();
            };

        });

    };
})(jQuery);


