 var CLIP_URL;
 var CLIP_ID;
 var CAPTION_URL;
 var CLIP_SITE_URL;
 var CLIP_SECCION;
 var INITIALIZED = false;

 function is_mobile() {
     var uagent = navigator.userAgent.toLowerCase();

      if ((uagent.search('iphone') > -1) ||
          (uagent.search('blackberry') > -1) ||
          //(uagent.search('ipad') > -1) ||
          (uagent.search('android') > -1) ||
          (uagent.search('ipod') > -1)) {
          return true;
      }
      return false;

 }

$(function() {  // main


   $('.mm-clip').live('click', function(e) {

       if (!is_mobile()) {
           e.preventDefault();

           if (CLIP_URL == $(this).attr('rel')) {
               return;
           }

           var targetOffset = $("#mm-contenido").offset().top;
        $('html,body').animate({scrollTop: targetOffset}, 500);

          CLIP_URL = $(this).attr('rel');
          CLIP_ID = $(this).attr('name');
          CAPTION_URL = $(this).attr('alt');
          CLIP_SITE_URL = $("#mm-code").attr("value");

          $('#mm-player').attr('href', CLIP_URL);
          $('#mm-player').attr('rel', CLIP_URL);


          // init_player();

           if (!$f('mm-player').isLoaded()) {
              $f('mm-player').load(function() {
                  cargar_clip(true);
              });
          }  else {
              cargar_clip(true);
           }

          $('#mm-clip-titulo').hide();
          $('#mm-clip-titulo').text($(this).attr('title'));
          $('#mm-clip-titulo').fadeIn();

          $('#breadcrumbs-title').text($(this).attr('title'));

       }
   });

    $('#mm-recientes .mm-clip').hover(function() {
		$(this).find('p').fadeIn();
		}, function() {
			$(this).find('p').fadeOut('fast');
		});

  // $('#mm-recientes').scrollable({'size': 4, 'nextPage': '#mm-rollder', 'prevPage': '#mm-rollizq'});
   $('#mm-recientes').scrollable({'next': '#mm-rollder', 'prev': '#mm-rollizq'});

   $('#mm-filtros a').live('click', function(e) {
   	  e.preventDefault();
	  //set_wait();
      $('#mm-filtros a').removeClass('current');
	  $(this).addClass('current');

//       var url = '';
//       var match = /(.{2})\/(.+)$/g.exec($(this).attr('href'));
//
//       if (match) {
//           if (match[0] != 'es') url += '/' + match[0];
//           url += '/ajax/' + match[1];
//       } else {
           url = '/ajax' + $(this).attr('href');
//       }

       //alert(url);

	    $('#mm-clips').load(url, '', function() {
	  	unset_wait();
	  });


   });

   $('#mm-menu a').live('click', function(e) {
   	  //set_wait();
      $('#mm-filtros').load('/filtros'+$(this).attr('href'));
	  $('#mm-clips').load('/ajax' + $(this).attr('href'), '', function(txt, st, xhr) {
	  	    //admin_links_discover();
	  	    unset_wait();
			////$('#mm-playback').hide();
			////$('#mm-navegador').fadeIn();
		});
      e.preventDefault();
   });

   $('li.mm-filtro-continente span').live('click', function() {
   	   $(this).parent().find('ul').toggle(450);
   });

    $("#mm-noticiaslabel").text('');
    setTimeout(init_promocionales, 2000);

});

function the_clip_url() {
    return CLIP_URL;
}

 function the_caption_url() {
    return CAPTION_URL;
}

 function the_clip_site_url() {
    return CLIP_SITE_URL;
}

function play_video() {
    if (! $f("mm-player").isLoaded()) {
       $f("mm-player").load();
    }

    //$f("mm-player").reset('ova');
    init_player();

    $f("mm-player").setPlaylist([{url:CLIP_URL, captionUrl:CAPTION_URL}]);

    IS_CLICKED = true;

     //$f("mm-player").reset('ova')();
     $f("mm-player").play();
   }

function cargar_clip(play) {
   //set_wait();
    //$f("mm-player").stop();

   $f("mm-player").setPlaylist([CLIP_URL]);
   if (play) {
       play_video();
   }


   $('#mm-descripcion').load('/descripcion/'+CLIP_ID+'/', '', function() {
      $('#mm-descripcion').hide();
      $('#mm-descripcion').fadeIn('fast');
    });

   $('#mm-relacionados').load('/relacionados/'+CLIP_ID+'/', '', function() {
      $('#mm-relacionados').hide();
      $('#mm-relacionados').fadeIn('fast');
      unset_wait();
    });
}


IS_FIRST = true;
IS_CLICKED = false;

 function pre_or_post() {
     if (IS_FIRST) {
         IS_FIRST = false;
         return 'pre-roll';
     } else {
         return 'post-roll';
     }
 }


function init_player() {
	flowplayer("mm-player", "/media/swf/flowplayer.commercial-3.2.7.swf", {

	    key: '#$bb4ed033774c4486ada',

        debug: false,

        onBeforeLoad: function() {
            quitar_promocionales();
            return true;
        },

        clip: {
            provider: 'lighttpd',
            autoPlay: true,
			autobuffering: false,
            eventCategory: 'Videos desde multimedia',

            onBeforeBegin: function() {
                this.unmute();
                return true;
            }

        },

        playlist: [
            // playlist entry with custom duration
            {url: the_clip_url()}

        ],

        logo: {

        },

		play: {
			replayLabel: 'Otra vez'
		},

        canvas: {
            backgroundColor: '#174F82',
            backgroundGradient: [0.3, 0]
        },

        plugins: {

            ova: {
               url: '/media/swf/ova.swf',
                autoPlay: true,
                ads: {
                    playOnce: true,
                    servers: [
                         {
                            "type": "OpenX",
                            "apiAddress":  'http://pubads.biz/www/delivery/fc.php'
                         }
                    ],
                    "schedule": [
                         {
                            "zone": "4",
                            "position": pre_or_post()
                         }
                    ]
                }
            },

            // the captions plugin
            /*
            captions: {
                url: '/media/swf/flowplayer.captions-3.2.3.swf',

                // pointer to a content plugin (see below)
                captionTarget: 'subsContent'
            },
            */

            /*
                configure a content plugin so that it
                looks good for showing subtitles
            */
            /*
            subsContent: {
                url:'/media/swf/flowplayer.content-3.2.0.swf',
                bottom: 5,
                height:40,
                backgroundColor: 'transparent',
                backgroundGradient: 'none',
                border: 0,
                textDecoration: 'outline',
                style: {
                    body: {
                        fontSize: 14,
                        fontFamily: 'Arial',
                        textAlign: 'center',
                        color: '#ffffff'
                    }
                }
            },
            */


            lighttpd: {
                url: '/media/swf/flowplayer.pseudostreaming-3.2.7.swf',
                queryString: escape('?client=FLASH&start=${start}')
            },

            controls: {
                url: '/media/swf/flowplayer.controls-3.2.5.swf',
				stop: true,
                bufferColor: '#5EA3DC',
                progressColor: '#174F82',
                buttonColor: '#4291D4',
                buttonOverColor: '#174F82',
                //backgroundGradient: 'none',
                backgroundColor: '#082439',
                tooltips: {
                    buttons: true,
                    fullscreen: 'Pantalla completa'
                }
            },

//            sharing: {
//               // load the sharing plugin
//               url: '/media/swf/flowplayer.sharing-3.2.1.swf',
//
//               pageUrl: CLIP_SITE_URL,
//
//               dock: {
//                    autoHide: 'always'
//               }
//		    },

            gatracker: {
                url: "/media/swf/flowplayer.analytics-3.2.2.swf",

                events: {
                    all: true
                },

                labels: {
                    start: "Video empezado",
                    play: "Play",
                    pause: "Pausa",
                    resume: "Resume",
                    seek: "Seek",
                    stop: "Stop",
                    finish: "Video terminado",
                    mute: false, // "Mute",
                    unmute: false, // "Unmute",
                    fullscreen: "Pantalla completa",
                    fullscreenexit: "Salir pantalla completa"
                },

                debug: false,
                accountId: "UA-11834651-1"
            }

        }
    }).ipad().onBeforeClick(function() {
        if (IS_CLICKED) return false;
    });


}

function quitar_promocionales() {
    if ($("#mm-promocionales").attr('id') == undefined) return;

    if ($f("mm-promocionales") != null && $f("mm-promocionales").isLoaded()) {
        $f("mm-promocionales").unload();
    }
    $("#mm-promocionales").remove();

    $("#mm-noticiaslabel").text('NOTICIAS RECIENTES');

    $.getFeed({
       url: '/telesur-rss/',
       success: function(feed) {
           $('#mm-feed').empty()
           max = 4;
           for (var i = 0; i<feed.items.length; i++) {
              $('#mm-feed').append('<div style="width:390px; margin-top:10px;" class="Negro_12px_bold"> <a href="'+feed.items[i].link+'">'+feed.items[i].title+'</a><div style="width:390px;background-image:url(/media/img/telesur/1px_new.jpg); background-repeat:repeat-x; margin-top:5px; margin-bottom:5px;" ><img src="/media/img/telesur/1px_new.jpg" /></div>');
              if (i>=max-1) break;
           }
       }
    });

}

function init_promocionales() {
    if ($("#mm-promocionales").attr('id') == undefined) return;

    $("#mm-noticiaslabel").text('PUBLICIDAD');

	flowplayer("mm-promocionales", "/media/swf/flowplayer.commercial-3.2.7.swf", {

        onLoad: function() {	// provide a Player event listener
		    this.mute();
	    },

        onMouseOver: function() {
            this.unmute();
            if (this.getPlugin('myContent')) {
                this.getPlugin('myContent').fadeOut();
            }
        },



	    key: '#$bb4ed033774c4486ada',

        debug: false,

        clip: {
            onFinish: function() {
               // setTimeout(quitar_promocionales, 5000);
            }
        },

        canvas: {
            backgroundColor: '#174F82',
            backgroundGradient: [0.3, 0]
        },



        plugins: {

            ova: {
               url: '/media/swf/ova.swf',
                autoPlay: true,
                ads: {
                    "notice": {
                        "message": ""
                    },
                    playOnce: true,
                    servers: [
                         {
                            "type": "OpenX",
                            "apiAddress":  'http://pubads.biz/www/delivery/fc.php'
                         }
                    ],
                    "schedule": [
                         {
                            "zone": "18",
                            "position": 'pre-roll'
                         }
                    ]
                }
            },

            controls: null,

            myContent: {

                // location of the plugin
                url: '/media/swf/flowplayer.content-3.2.0.swf',

                // display properties
                bottom: 0,
                right: 0,
                width: 105,
                margin:0,
                padding:0,
                backgroundColor: 'transparent',
                borderRadius: 0,
                border: 0,
                height: 110,
                // "inline" styling (overrides external stylesheet rules),
                    style: {
                        '.title': {
                            background: null
                        }
                    },

                // styling properties
                //borderRadius: 10,
                //backgroundImage: 'url(/media/img/mute.png)',

                // linked stylesheet
                //stylesheet: 'content-plugin.css',

                // "inline" styling (overrides external stylesheet rules),


                /*
                    initial HTML content. content can also be fetched from the HTML document
                    like we did in the example above. see the source code for that.
                */
                html: '<img id="mm-adsmute" align="left" padding="0" margin="0" src="/media/img/mute.png" />'

            }

        }
    }).load().play();

}

var set_wait = function () {
 $('body').addClass('wait');
 $('a').addClass('wait');
}

var unset_wait = function () {
 $('body').removeClass('wait');
 $('a').removeClass('wait');
}

var set_filtro_nombre = function () {
	span = $('span#mm-valor-nombre');
	slug = span.attr('rel');
	nombre = $('#mm-filtro-'+slug).text();
	span.text(nombre);

}
var set_tipo_nombre = function () {
    span = $('span#mm-tipo-nombre');
    slug = span.text();
    span.text(traducir_slug(slug));
}

function traducir_slug(slug) {
	switch (slug) {
		case 'Latinoamerica':
            if (LANGUAGE_CODE=='en') return 'Latin America';
            if (LANGUAGE_CODE=='pt') return 'América Latina';
		    return 'Latinoamérica';
		case 'Politica':
            if (LANGUAGE_CODE=='en') return 'Politics';
            return 'Política';
		case 'Economia':
            if (LANGUAGE_CODE=='en') return 'Economy';
            if (LANGUAGE_CODE=='pt') return 'Economia';
            return 'Economía';
        case 'Medio-ambiente':
            if (LANGUAGE_CODE=='en') return 'Environment';
            if (LANGUAGE_CODE=='pt') return 'Meio ambiente';
            return 'Medio ambiente';
        case 'Corresponsales':
            if (LANGUAGE_CODE=='en') return 'Correspondants';
            if (LANGUAGE_CODE=='pt') return 'Correspondentes';
            return 'corresponsales';
        case 'Deportes':
            if (LANGUAGE_CODE=='en') return 'Sports';
            if (LANGUAGE_CODE=='pt') return 'Esportes';
            return 'corresponsales';

		default:
		    return slug.replace(/-/g, ' ');
	}
}
