/*
 * Visualizador de Galerias de Picasa Web Albums
 * Las siguientes funciones cargan y presentan la galeria de imagenes
 * almacenadas en Picasa Web Albums
 */

// Lista de albunes
function loadAlbumsList(data, status) {
	
	var albums = data.feed.entry;
	var initgal = 0;

	$.each(albums, function() {
	    $("<li class='album'><a>" + this.title.$t + "</a></li>").appendTo("div#gallery-albums > ul")
		.children("a").attr('href', this.link[0].href)
		.click(function() {
		    $("div#gallery-photos > ul > li ").remove();
		    $("div#gallery-albums ul li a").removeClass('active');
		    $(this).addClass('active');

		    $.ajax({ url: this.href + '&thumbsize=104c&imgmax=576',
		        success: showPhotoList,
		        dataType: 'jsonp'
		    });
		    return false;
		});

	    // Inicializando albums
	    if (initgal == 0) {
	        $.ajax({ url: this.link[0].href + '&thumbsize=104c&imgmax=576',
	            success: showPhotoList,
	            dataType: 'jsonp'
	        });
	        $('#gallery-albums ul a').addClass('active');
	        initgal = 1;
	    }
	});
}

// Displiga una lista desordenada (ul) con los thums de las fotos dentro del contenedor indicado
function showPhotoList(data, status) {
    
    // cargamos el arreglo de fotos
    var photos = data.feed.entry;
	
	$.each(photos, function() {
	    // Obteniendo informacion de la foto
	    var mg = this.media$group;
	    var orig = mg.media$content[0];
	    var desc = mg.media$title.$t + "\n" + mg.media$description.$t;

	    // Creando thumb
	    $("<li><a class='photo thumb' href='" + orig.url + "'><img  src='" + mg.media$thumbnail[0].url + "' title='" + desc + "'/></a> </li>")
		    .appendTo("div#gallery-photos > ul ");

	    $('li a.thumb').lightBox({
	        fixedNavigation: true,
	        overlayBgColor: '#4F2119',
	        overlayOpacity: 0.5,
	        imageLoading: 'http://www.visitehotelesdemexico.com/restaurantes/assets/css/imgs/lightbox-ico-loading.gif',
	        imageBtnClose: 'http://www.visitehotelesdemexico.com/restaurantes/assets/css/imgs/lightbox-btn-close.gif',
	        imageBtnPrev: 'http://www.visitehotelesdemexico.com/restaurantes/assets/css/imgs/lightbox-btn-prev.gif',
	        imageBtnNext: 'http://www.visitehotelesdemexico.com/restaurantes/assets/css/imgs/lightbox-btn-next.gif',
	        containerResizeSpeed: 350,
	        txtImage: 'Foto',
	        txtOf: 'de'

	    });		    
		    
	});		 				
}		


/* 
* Funcion principal para carga de Feed de datos Picasa 
* 
* showPicasaPhotoList(picasauser, thumsize, imgmax,  maxresults);
*
*/
function showPicasaWebPhotoList(picasaUserName, thumbSize, imgMax, maxResults) {
       
    var PICASA_FEED_BASE = 'http://picasaweb.google.com/data/feed/api/user/';
    var picasaUserFeed = PICASA_FEED_BASE + picasaUserName + '/?alt=json-in-script&kind=photo&hl=es';

    // if (albumId != null) { picasaUserFeed = picasaUserFeed + '&albumid=' + albumId; }
    if (thumbSize != null) { picasaUserFeed = picasaUserFeed + '&thumbsize=' + thumbSize; } // Si thumSize es definido
    if (imgMax != null) { picasaUserFeed = picasaUserFeed + '&imgmax=' + imgMax; } // Si imgmax es definido       
    if (maxResults != null) { picasaUserFeed = picasaUserFeed + '&max-results=' + maxResults; } // Si maxResults es definido
            
    // Cargando Feed de datos
    $.ajax({ url: picasaUserFeed,
        success: showPhotoList,
        dataType: 'jsonp'
        });
}

// Funcion principal para carga de Feed de datos Picasa
function showPicasaWebGallery(picasaUserName, thumbSize, imgmax, maxResults) {

    var PICASA_FEED_BASE = 'http://picasaweb.google.com/data/feed/api/user/';
    var picasaUserFeed = PICASA_FEED_BASE + picasaUserName + '/?alt=json-in-script&kind=album&hl=es';

    if (thumbSize != null) { picasaUserFeed = picasaUserFeed + '&thumbsize=' + thumbSize; } // Si thumSize es definido    
    if (imgmax != null) { picasaUserFeed = picasaUserFeed + '&imgmax=' + imgmax; } // Si imgmax es definido       
    if (maxResults != null) { picasaUserFeed = picasaUserFeed + '&max-results=' + maxResults; } // Si maxResults es definido

    // Cargando Feed de datos
    $.ajax({ url: picasaUserFeed,
        success: loadAlbumsList,
        dataType: 'jsonp'
    });
}

/*
* Visualizador de videos de YouTube
* Las siguientes funciones cargan y presentan la lista de videos
* en YouTube
*/

// Carga reproductor de video
function loadVideo(playerUrl, autoplay) {
    swfobject.embedSWF(
              playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
              (autoplay ? 1 : 0), 'player', "560", "340", '9.0.0', false,
              false, { allowfullscreen: 'true' });
}

// Despliega un listado de los videos encontrados
function showMyYouTubeVideos(data) {
    var feed = data.feed;
    var entries = feed.entry || [];
    var initVideo = 0;

    // Si existen videos
    if (entries.length > 0) {
        $.each(entries, function() {
            var video = this;
            var title = video.title.$t.substr(0, 40);
            var thumbnailUrl = video.media$group.media$thumbnail[0].url;
            var playerUrl = video.media$group.media$content[0].url;

            $('<li><a href=""><img src="' + thumbnailUrl + '"/><br />' + title + '</a></li>').appendTo('ul.videos ')
                .click(function() {
                    loadVideo(playerUrl, true);
                    return false;
                });

            // Si es la primera vaz que se carga la lista de videos
            if (initVideo == 0) {
                loadVideo(playerUrl, false);
                initVideo = 1;
            }
        });
    }
}


/*
* Visualizador de Comentarios sobre el restaurante Socio 
* Las siguientes funciones cargan y presentan la lista de comentarios
* sobre un restaurante especifico.
*/
function showCommentsList(data, maxComments, status) {

    var tplCommentsList = '';
    var totalComments = $(data).find('comment').length

    if (totalComments > 0) {
        $(data).find('comment').each(function() {

            var title = $(this).find('title').text();
            var body = $(this).find('body').text().replace(/<\/?[^>]+>/gi, '');
            var author = $(this).find('author').text();
            var pubdate = $(this).find('pubdate').text();
            var rate = $(this).find('rate').text();

            // Template
            tplCommentsList += '<li>';
            tplCommentsList += '<h4>' + title + '</h4>';
            tplCommentsList += '<div>' + body + '</div>';
            tplCommentsList += '<span>Por: ' + author + '</span> <br /> ';
            tplCommentsList += '<span>Publicado el: ' + pubdate + '</span>';
            tplCommentsList += '<br/><span> Valoraci&oacute;n:' + '<img src="../assets/css/imgs/star-' + rate + '.gif"/></span>';
            tplCommentsList += '</li>';

        });

        $(tplCommentsList).appendTo('ul.commentsList');
    } else {
        $("<li>No se encontraron comentarios.</li>").appendTo('ul.commentsList');
    }
    
}


// Cargando listado de comentarios
function loadCommentsList(pid, maxComments) {
    // Cargando Feed de datos
    commentFeed = '../assets/feed/comments-rss.aspx' + '?pid=' + pid + '&maxComments=' + maxComments;    

    $.ajax({ url: commentFeed,
        success: showCommentsList,
        dataType: 'xml'
    });
}


// Mapa interactivo de Google v3

/*
* Crea un mapa y agrega el punto en base a la infotmacion proporcionada
* 
* gMap_showPoint(altText, lat, lng, zoom, cLat, cLng)
*
* altText = Informacion del punto
* lat = Latitud del punto
* lng = Longitud del punto
* zoomStart = Nivel de zoom inicial
* cLat = Latitud inicial del mapa
* cLng = Longitud inicial del mapa
* 
*/
function gMap_showPoint(altText, lat, lng, zoomStart, cLat, cLng) {

    var mapCenter;

    // Localizacion del punto 
    var latlng = new google.maps.LatLng(lat, lng);
    var mapCenter = new google.maps.LatLng(lat, lng);
    
    if (cLat != null) {
        mapCenter = new google.maps.LatLng(cLat, cLng);        
    }   
	
	var myOptions = {
	    zoom: zoomStart,
		center: mapCenter,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		title: altText
	});

}
    
    
    


