$( window ).load( function(){
	getFaceBookUpdates();
	getTwitterUpdates();
	getLatestPodcast();
	initializeMenu();
	debug( $.browser );
	var location = window.location.href;
	var pageParam = "?page=";
	var indexOfPageParam = location.indexOf( pageParam );
	if( indexOfPageParam >= 0 ){
		pageToLoad = location.substring( indexOfPageParam + pageParam.length );
		debug( "Page to load: " + pageToLoad );
		loadPage( pageToLoad );
	}else{
		$("#content").show();
        setStyles();
		showSocialNetworks();
		startRotatingMenu();
		initPackagesMenu();
	}
});

function loadPage( url ){
    $("#labelDiv").hide();
    eval( ( $("#onUnloadScripts").html() + "" ).replace( "<!--" , "" ).replace( "-->" , "" ) );
	showWait( function (){
		$.get( url , function( data ){
	        $("#content").html(data);
	        eval( ( $("#onLoadScripts").html() + "" ).replace( "<!--" , "" ).replace( "-->" , "" ) );
	        setStyles();
	        hideWait( null );
	    });
	});
	return false;
}

function initializeMenu(){
    $(".lavaLamp").lavaLamp({
        fx: "backout",
        speed: 500,
        click: function(event, menuItem) {
            return false;
        }
    });
}

function initializeOptions(){
	$(".titleOption")
		.hover( function(){ 
		        goHOVER( this );
		        $( this ).animate({ paddingLeft: "30px" } , 250 );
		    }, 
		    function(){
		        goOUT( this );
		        $( this ).animate({ paddingLeft: "20px" } , 250 );
		    })
		.click( clickOption );
}

function showWait( callback ){
    $("#content").fadeOut( 200 , function(){
        $("#wait").fadeIn( 200 , callback );
    });
}

function hideWait( callback ){
    $("#wait").fadeOut( 200 , function(){
        $("#content").fadeIn( 200 , callback );
    });
}

function showSocialNetworks(){
    $("#socialNetworksDIV").slideDown( 400 );
}

function hideSocialNetworks(){
    $("#socialNetworksDIV").slideUp( 400 );
}

function clickOption(){
	var titleOptionsSELECTED = $(this.parentNode).children(".titleOptionSELECTED");
	if( titleOptionsSELECTED.length > 0 ){
		titleOptionsSELECTED
		    .animate({ paddingLeft: "20px" } , 50 )
			.hover( function(){ 
                    goHOVER( this );
                    $( this ).animate({ paddingLeft: "30px" } , 250 );
			    }, 
			    function(){
			        goOUT( this );
			        $( this ).animate({ paddingLeft: "20px" } , 250 );
			    })
			.click( clickOption )
			.children( ".subOptions" )
			.slideUp()
			.children( ".titleOptionSELECTED" )
			.hover( function(){ 
			        goHOVER( this );
			        $( this ).animate({ paddingLeft: "30px" } , 250 );
                }, 
                function(){
                    goOUT( this );
                    $( this ).animate({ paddingLeft: "20px" } , 250 );
                })
			.click( clickOption )
			.each( function(){ goOUT( this ); $( this ).animate({ paddingLeft: "20px" } , 250 ); } );
		goOUT( titleOptionsSELECTED[0] );
		$( "#slideshow IMG" ).stop(true,true).hide().removeClass( "active" );
		$( "#slideshow" ).html( "" );
		doSlideshow = false;
		sliding = false;
		clearTimeout( timeoutId );
	}
	goSELECTED( this );
	$(this)
		.unbind( "mouseenter" )
		.unbind( "mouseleave" )
		.unbind( "click" )
		.css({ "padding-left": "30px" } );
	var textToShow = $(this).children( ".textToShow" );
	var subOptions = $(this).children( ".subOptions" );
	var imagesToShow = $(this).children( ".imagesToShow" );
	if( textToShow.length > 0 ){
		$( "#text-container" ).fadeOut( function(){
			$(this).fadeIn()
				.find("#text-container-content")
				.html( textToShow.html() );
		});
	}else{
		$( "#text-container" ).fadeOut();
	}
	if( imagesToShow.length > 0 ){
		var baseDir   = imagesToShow[0].getAttribute( "baseDir" );
		var imgNames  = imagesToShow[0].getAttribute( "imgNames" ).split( "|" );
		var slideShow = document.getElementById( "slideshow" );
		
		if( baseDir.charAt( baseDir.length -1 ) != "/" ){
			baseDir += "/";
		}
		
		for ( var i = 0; i < imgNames.length; i++) {
			var imgName = imgNames[i];
			var img = document.createElement( "IMG" );
			debug( baseDir + imgName );
			img.src = baseDir + imgName;
			slideShow.appendChild( img );
		}
		doSlideshow = true;
		firstSlide = true;
		slideSwitch();
	}
	if( subOptions.length > 0 ){
		subOptions.slideDown();
	}
}
var doSlideshow = false;
var sliding = false;
var firstSlide = true;
var timeoutId = -1;
var SLIDE_MAX_WIDTH_H = 300;
var SLIDE_MAX_HEIGHT_H = 226;

function slideSwitch() {
	if( sliding ) return;
	sliding = true;
    var $active = $( "#slideshow .active" );
    var $slideChildren = $('#slideshow').children();
    if ( $active.length == 0 ) $active = $( $slideChildren[ $slideChildren.length - 1 ] );
    var $next = ( $active.next().length )? $active.next() : $( $slideChildren[0] ) ;
    var activeWidth = ($active.width()>100)?$active.width():SLIDE_MAX_WIDTH_H;
    var activeHeight = ($active.height()>100)?$active.height():SLIDE_MAX_HEIGHT_H;
    var nextWidth = ($next.width()>100)?$next.width():SLIDE_MAX_WIDTH_H;
    var nextHeight = ($next.height()>100)?$next.height():SLIDE_MAX_HEIGHT_H;
    var currentStyle={top:0,left:0,width:activeWidth,height: activeHeight };
    var hideStyle = {top:180,left:180,width:0,height:0};
    var nextStyle = {top:0,left:0,width: nextWidth,height: nextHeight};
    $active.animate( hideStyle , 500 , function(){
    	$active.hide().removeClass( "active" ).css(currentStyle);
        $next.css( hideStyle ).animate( nextStyle , 500 , function(){
            if( $slideChildren.length <= 1 ){
                doSlideshow = false;
            }
            if( doSlideshow ){
            	timeoutId = setTimeout( slideSwitch , 4000 );
            }
            sliding = false;
        }).addClass( "active" );
    });
    
    if( firstSlide ){
    	$active.stop( true, true );
    	firstSlide = false;
    }
}

function initializeQuienesSomos(){
    $( "#quienesTable" ).find("IMG").css( {opacity: 0.2} ).hover(
                function( e ){
                    $(this).stop(true,true).css("border","solid #FFFF00 1px").animate( { opacity: 1.0 } );
                    $("#labelDiv").css({ "display" : "block",top: ( e.pageY - 30 ),left: ( e.pageX + 20 )}).stop(true,true).fadeIn().find("#labelText").html( this.getAttribute( "alt" ) );
                },
                function(){
                    $(this).css("border","solid #7777BB 1px").animate( { opacity: 0.2 } , 800 );
                    $("#labelDiv").fadeOut( function(){$(this).css( "display" , "none" ).find("#labelText").html("");});
                }
        )
        .mousemove( function( e ){
            $("#labelDiv").css({
                top: ( e.pageY - 30 ),
                left: ( e.pageX + 20 )
            });
        }).click( function(){
            var bioHtml = $(this.parentNode).find(".bio").html();
            $("#showBicoContainerDIV").stop(true,true).fadeOut("slow",function(){
                $(this).fadeIn("slow").find("#showBioDIV").html( bioHtml ); 
            });
        });
}

function initializeVideos(){
    var url = "http://gdata.youtube.com/feeds/users/malinalcodesconocido/uploads?max-results=7&format=5&alt=json&orderby=published&callback=?";
    debug( url );
    $.getJSON( url , function( data ) {
       debug( data );
       var playList = document.getElementById("playList");
       for ( var i = 0; i < data.feed.entry.length; i++) {
           var entry = data.feed.entry[i];
           var thumbnail = document.createElement("IMG");
           thumbnail.src    = entry.media$group.media$thumbnail[0].url;
           thumbnail.width  = entry.media$group.media$thumbnail[0].width;
           thumbnail.height = entry.media$group.media$thumbnail[0].height;
           thumbnail.alt    = entry.title.$t;
           thumbnail.setAttribute( "videoURL" , entry.link[0].href );
           debug( "["+i+"]" + entry.link[0].href );
           debug( "["+i+"]" + entry.title.$t );
           debug( "["+i+"]" + entry.media$group.media$thumbnail[0].url );
           playList.appendChild( thumbnail );
       }
       $( playList ).find("IMG").css( {opacity: 0.5, width: "120px", height: "90px"} ).hover(
               function( e ){
                   $(this).stop(true,true).css("border","solid #FFFF00 1px").animate( { opacity: 1.0 } );
                   $("#labelDiv").css({ "display" : "block",top: ( e.pageY - 30 ),left: ( e.pageX + 20 )}).stop(true,true).fadeIn().find("#labelText").html( this.getAttribute( "alt" ) );
               },
               function(){
                   $(this).css("border","solid #7777BB 1px").animate( { opacity: 0.5 } );
                   $("#labelDiv").fadeOut( function(){$(this).css( "display" , "none" ).find("#labelText").html("");});
               }
       )
       .mousemove( function( e ){
           $("#labelDiv").css({
               top: ( e.pageY - 30 ),
               left: ( e.pageX + 20 )
           });
       }).click( function(){
           var $playerTD = $("#playerTD").html("");
           var videoURL = $(this).attr("videoURL");
           var videoID = videoURL.substring( videoURL.indexOf( "?v=" ) + 3 ).replace( "&" , "?" );
           debug( "videoId = " + videoID );
           videoURL = "http://www.youtube.com/v/" + videoID + "fs=1&rel=0&amp;color1=0x234900&amp;color2=0x4e9e00&amp;border=1" ;
           var html = 
               '<object width="400" height="324">' +
               '    <param name="movie" value="' + videoURL + '"></param>' + 
               '    <param name="allowFullScreen" value="true"></param>'+
               '    <param name="allowscriptaccess" value="always"></param>' + 
               '    <embed src="' + videoURL + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="400" height="324"></embed>'+
               '</object>';
           $playerTD.html( html );
       });
    });
}
var apiKey="bc143a1a4c49ed5eff7b5688d01c7664";
var bichosFlickrId="48128532@N07";
function showFlikerSets(){
    var url="http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=" + apiKey + "&user_id=" + bichosFlickrId + "&format=json&jsoncallback=?";
    debug(url);
    $(".flickrNavControls").fadeOut();
    $(".flickrTitle").html( "Galer&iacute;as de Im&aacute;genes" );
    $.getJSON( url , function(data) {
        if( data.stat == "ok" ){
            var photosetsArray = data.photosets.photoset;
            var html = "<table align='center'><tbody><tr><td width='30%'/><td width='30%'/><td width='30%'/></tr>";
            for ( var i = 0; i < photosetsArray.length; i++) {
                if( i==0){
                    html += "<tr>";
                }else if( i%3 == 0 ){
                    html += "</tr><tr>";
                }
                var item = photosetsArray[ photosetsArray.length - i - 1];
                var title = item.title._content.replace(/\"/g,"\\\"");
                var thumbnailURL = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.primary + "_" + item.secret + "_s.jpg";
                var photoURL = "javascript:showFlickerSetPictures( \"" + item.id + "\" , 1 , \"" + title + "\" );";
                debug( thumbnailURL );
                debug( "photoURL:" + photoURL );
                html += "<td align='center' valign='middle' style='padding:40px;'>" +
                        " <div class='round' align='center'>" +
                        "     <a href='" + photoURL + "'>" +
                        "         <img style='border: solid #8888FF 2px;' src='" + thumbnailURL + "'/>" +
                        "     </a>" +
                        "     <br/><b style='color:#77FFDD;'>" + item.title._content +"</b>" +
                        " </div>" + 
                        "</td>";
                if( i == photosetsArray.length - 1 ){
                    html += "</tr>";
                }
            }
            html+="</table></tbody>";
            $("#picturesContainer").html(html);
            setStyles();
        }
    });
}
var currentFlickrPage;
var currentFlickrSet;
var currentFlickerTitle;
function showFlickerSetPictures( setId , page , photsetTitle ){
    var perPage=9;
    var currentFlickerTitle = photsetTitle.replace(/\"/g,"\\\"");
    var url="http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=" + setId + "&api_key=" + apiKey + "&user_id=" + bichosFlickrId + "&per_page=" + perPage + "&page=" + page + "&format=json&jsoncallback=?";
    debug(url);
    $.getJSON( url , function(data) {
        if( data.stat == "ok" ){
            flickrTitle="";
            var photosArray = data.photoset.photo;
            currentFlickrPage = data.photoset.page;
            currentFlickrSet  = data.photoset.id;
            $(".flickrTitle").html( currentFlickerTitle );
            var navControlsHtml = "<a href=\"javascript:showFlikerSets();\">&lt;&lt;-- Regresar a galer&iacute;as</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            for( var i = 1; i <= data.photoset.pages ; i++ ){
                if( i != currentFlickrPage ){
                    navControlsHtml += "<a href='javascript:showFlickerSetPictures( \"" + currentFlickrSet + "\" , " + i + " , \"" + currentFlickerTitle + "\" );'>";
                }
                navControlsHtml += i;
                if( i != currentFlickrPage ){
                    navControlsHtml += "</a>";
                }
                navControlsHtml += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            }
            $(".flickrNavControls").html( navControlsHtml ).fadeIn();
            var html = "<table align='center'><tbody>";
            for ( var i = 0; i < photosArray.length; i++) {
                if( i==0){
                    html += "<tr>";
                }else if( i%3 == 0 ){
                    html += "</tr><tr>";
                }
                var item = photosArray[i];
                var thumbnailURL = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_m.jpg";
                var photoURL = "http://www.flickr.com/photos/losbichosdemalinalco/" + item.id;
                debug( photoURL );
                html += "<td align='center' valign='middle'>" +
                        " <div class='round' align='center'>" +
                        "     <a href='" + photoURL + "'>" +
                        "         <img style='border: solid #8888FF 2px;' src='" + thumbnailURL + "'/>" +
                        "     </a>" +
                        "     <br/>" + item.title +
                        " </div>" + 
                        "</td>";
                if( i == photosArray.length - 1 ){
                    html += "</tr>";
                }
            }
            html+="</table></tbody>";
            $("#picturesContainer").html(html);
            setStyles();
        }
    });
}

function showPodcasts(){
	var url = "http://www.ivoox.com/podcast-podcast-malinalco-desconocido_fg_f112553.551221_filtro_1.xml";
	debug(url);
	$.jGFeed( url ,
		function(feeds){
		  var html = "";
		  if(!feeds){
		    html = "No se encontraron podcasts...";
		  }
		  for(var i=0; i<feeds.entries.length; i++){
		    var entry = feeds.entries[i];
		    var podcastId = entry.link.substring( entry.link.indexOf("_rf_") + 4 ).replace(".html","");
		    debug( "title[" + i + "] : " + entry.title );
		    debug( "link[" + i + " ] :" + entry.link );
		    debug( "castId[" + i + "]:" + podcastId );
		    html +=
			    "<div class='round'>" +
	    		"     <table><tbody>" +
	    		"         <tr>" +
	    		"             <td colspan='2'>" +
	    		"                 <b class='title'>" + entry.title + "</b>" +
	    		"             </td>" +
	    		"         </tr>" +
	    		"         <tr>" +
	    		"             <td align='justify'>" +
	    		"                 <p>"+ entry.content + "</p><br/>" +
	    		"                 <object width='173' height='30' type='application/x-shockwave-flash' data='http://www.ivoox.com/playerivoox_ep_" + podcastId + ".html'>" +
	    		"						<param name='movie' value='http://www.ivoox.com/playerivoox_ep_" + podcastId + ".html'></param>" +
	    		"						<param name='allowFullScreen' value='true'></param><param name='wmode' value='transparent'></param>" +
	    		"						<embed src='http://www.ivoox.com/playerivoox_ep_" + podcastId +".html' type='application/x-shockwave-flash' allowfullscreen='true' wmode='transparent' width='173' height='30'></embed>" +
	    		"				  </object>" +
	    		"				  <a href='" + entry.link + "'> Descargar</a>" +
	    		"             </td>" +
	    		"         </tr>" +
	    		"     </tbody></table>" +
	    		"</div><br/>";
		  }
		  debug( "html[" + i +"]:" + html.replace(/[<]/g,"&lt;").replace(/[>]/g,"&gt;") );
		  $("#podcastContainer").html(html);
	      setStyles();
	}, 10);
}

function getBloggerPosts(){
    var maxResults = 5;
    var bichosBloggerId = "1757466998842748260";
    var url = "http://www.blogger.com/feeds/" + bichosBloggerId + "/posts/summary?&alt=json&callback=?&max-results=" + maxResults;
    debug( url );
    $.getJSON( url , function( data ) {
        data;
        var html="";
        for ( var i = 0; i < data.feed.entry.length; i++) {
            var entry = data.feed.entry[i];
            html += "<div class='round'>" +
            		"     <table><tbody>" +
            		"         <tr>" +
            		"             <td colspan='2'>" +
            		"                 <b class='title'>" + entry.title.$t + "</b>" +
            		"             </td>" +
            		"         </tr>" +
            		"         <tr>" +
            		"             <td>" +
            		"                 " + (( entry.media$thumbnail != null )?"<img style='border: solid #8888FF 2px;' src='" + entry.media$thumbnail.url +"'/>":"") +
            		"             </td>" +
            		"             <td align='justify'>" +
            		"                 <p>"+ entry.summary.$t +"... <a style='color:#8888FF;font-weight:bold;' href='" +entry.link[4].href+ "'>continuar leyendo</a></p>" +
            		"             </td>" +
            		"         </tr>" +
            		"     </tbody></table>" +
            		"</div>\n<br/>";
        }
        $("#bloggerPostsTD").html( html );
        setStyles();
    });
}

function goOUT( elem ){
	var className = elem.className;
	if( className != null ){
		if( className.indexOf('HOVER') >=0 ){
			elem.className = className.substring( 0 , className.indexOf('HOVER') );
		}
		if( className.indexOf('SELECTED') >=0 ){
			elem.className = className.substring( 0 , className.indexOf('SELECTED') );
		}
	}
}

function goHOVER( elem ){
	goOUT( elem );
	elem.className = elem.className+'HOVER';
}

function goSELECTED( elem ){
	goOUT( elem );
	elem.className = elem.className+'SELECTED';
}

function setStyles(){
    $(".round").before( 
            "<div class=\"round-top-left\">" +
            "   <div class=\"round-top-right\">" +
            "       <div class=\"round-top-middle\"></div></div></div>"
    ).after(
            "<div class=\"round-bottom-left\">" +
            "   <div class=\"round-bottom-right\">" +
            "       <div class=\"round-bottom-middle\"></div></div></div>"
    ).wrap(
            "<div class=\"round-middle-left\"><div class=\"round-middle-right\"><div class=\"round-center\"></div></div></div>" 
    ).removeClass("round").addClass("rounded");
}

function getTwitterUpdates(){
	var url = "http://twitter.com/status/user_timeline/bichosmalinalco.json?count=3&callback=?"; 
	debug( url );
	$.getJSON( url , function(data) {
	    debug( "response: " + data );
		var html = "";
		for ( var i = 0; i < data.length; i++) {
			var update = data[i];
			html += "<div class=\"post\">";
			html += update.text;
            html += "</div>";
		}
		$("#twitterUpdatesDiv").html( html );
	});
}
function getFaceBookUpdates(){
    $("#faceBookUpdatesDiv").html( "" );
	var url = "http://www.facebook.com/feeds/page.php%3Fid%3D329292726924%26format%3Datom10";
    debug( "FACEBOOK >>> " + url );
    $.jGFeed( url , function( feeds ){
        debug( "FACEBOOK >>> response received!!!" );
        var html = "";
        if(!feeds){
          debug("FACEBOOK >>> no hay entries");
          html = "No hay no se encontraron actualizaciones...";
        }
        for( var i=0 ; i < feeds.entries.length ; i++ ){
          if( i > 3 ){
              break;
          }
          var entry = feeds.entries[i];
          var indexOfImage = entry.content.indexOf('<img src="');
          var img = null;
          if( indexOfImage != -1 ){
              img = entry.content.substring( indexOfImage + 10 , entry.content.indexOf('"' , indexOfImage + 10 ));
          }
          debug( "FACEBOOK >>> title : " + entry.title );
          debug( "FACEBOOK >>> link :" + entry.link );
          debug( "FACEBOOK >>> img :" + img );
          html += "<div class=\"post\">" +
          		"<a href='" + entry.link + "' target='_new' style='text-decoration:none;'>";
          if( img != null ){
            html += "<img src='" + img + "' width='55px' height='45px' style='display:block;float:left;'/>";
          }
          html += entry.title.substring(0,120) + "...</a>"
               +  "</div>";
        }
        $("#faceBookUpdatesDiv").html( html );
    }, 10);
}
function initPackagesMenu(){
    debug("Inicializando el menu");
    $('div.packagesMenu ul li a').hover(function() {  
      if ($(this).is(':animated')) {
        $(this).addClass("active").stop().animate({width: "240px"}, {duration: 450, easing: "easeOutQuad", complete: "callback"});
      } else {
        $(this).addClass("active").stop().animate({width: "240px"}, {duration: 400, easing: "easeOutQuad", complete: "callback"});
      }
    }, function () {
      if ($(this).is(':animated')) {
        $(this).removeClass("active").stop().animate({width: "30px"}, {duration: 400, easing: "easeInOutQuad", complete: "callback"})
      } else {
        $(this).removeClass("active").stop(':animated').animate({width: "30px"}, {duration: 450, easing: "easeInOutQuad", complete: "callback"});
      }
    });
}
function getLatestPodcast(){
	var url = "http://www.ivoox.com/podcast-podcast-malinalco-desconocido_fg_f112553.551221_filtro_1.xml";
	debug(url);
	$.jGFeed( url ,
		function(feeds){
		  var html = "";
		  if(!feeds){
			debug("no hay entries");
		    html = "No hay podcast...";
		  }
		  if( feeds.entries.length > 0 ){
		    var entry = feeds.entries[0];
		    var podcastId = entry.link.substring( entry.link.indexOf("_rf_") + 4 ).replace(".html","");
		    debug( "title : " + entry.title );
		    debug( "link :" + entry.link );
		    debug( "castId:" + podcastId );
		    html += 
		    "<div class=\"post\">" +
		    "  <object width='173' height='30' type='application/x-shockwave-flash' data='http://www.ivoox.com/playerivoox_ep_" + podcastId + ".html'>" +
    		"    <param name='movie' value='http://www.ivoox.com/playerivoox_ep_" + podcastId + ".html'></param>" +
    		"    <param name='allowFullScreen' value='true'></param><param name='wmode' value='transparent'></param>" +
    		"    <embed src='http://www.ivoox.com/playerivoox_ep_" + podcastId +".html' type='application/x-shockwave-flash' allowfullscreen='true' wmode='transparent' width='173' height='30'></embed>" +
    		"  </object>" +
            "</div>";
		  }
		  $("#podcastUpdatesDiv").html( html );
	}, 10);
}
function debug( str ){
    //$("#debug").html( $("#debug").html() + "<br/>" + str );
}

