//js

//extending native object
//with size method
//usage: var size = Object.size(myArray);
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
//Usage: alert(‘foo.bar exists: ‘+isset(‘foo.bar’));
//http://verens.com/archives/2005/07/25/isset-for-javascript/
isset = function(e) {
  try {
    if (eval(e)) {}
  }
  catch(err) {
    return false;
  }
  return true;
}

//end utilities

/*
* Checks if we can use the browser for time
* @param int allowed_diff eg 360 seconds
* @return boolean
*/
function can_use_browser_time(allowed_diff)
{
    //BROWSER
    var currentDate = new Date();
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var month = parseInt(currentDate.getMonth()+1);
    month = (month<10 ? '0'+month : month);
    
    var day = parseInt(currentDate.getDate());
    day = (day<10 ? '0'+day : day);
    
    var brtoday =  currentDate.getFullYear()+' '+month+' '+day;
    var btime = (hours<10 ? '0'+hours : hours) + ':'+(minutes<10 ? '0'+minutes : minutes);
    
    //timestamp 
    var br_tmst = toTimestamp(brtoday+' '+btime);
    
    mylog('browser tmst:' +br_tmst +'('+brtoday+' | '+btime+')');
    
    //SERVER
    var server_date = today +' '+server_hour;
    var srv_tmst = toTimestamp(server_date);
    mylog('srv_tmst:' +srv_tmst +'('+server_date+')');
    
    //COMPARE
    timediff = parseInt(srv_tmst) - parseInt(br_tmst);
    mylog('timediff' + timediff);
    
    if( timediff > -allowed_diff && timediff < allowed_diff ){
        mylog('can use browser time');
        return true;
    }else{
        mylog('use server time');
        return false;
    }
    
}



function detect_live_new()
{
    var now_time = thetime();//17:36
    
    var do_reload = should_reload();
    if(do_reload){
        mylog('reload page');
        window.location.reload(true);
    }
    
    if(yesterday){
        //we're seeing yesterdays archive
        //assumes page is reloaded at change from
        //07:xx to 08:xx
        //there's no live of yesterday..
        mylog('yesterdays archive.. nothing to do');
        return;
    }    
    
    var current_broadcast = get_current_broadcast();//17:00
    var correct_broadcast = get_broadcast_of_hourminute(now_time,broad_array);
    mylog('correct broadcast: '+correct_broadcast);
    
    if(correct_broadcast != false && current_broadcast != correct_broadcast){
        mylog('NEW BROADCAST:' +correct_broadcast +' (old: '+current_broadcast+')');
        
        //change current broadcast to new
        set_current_broadcast(correct_broadcast);
        
        //reload archive
        refresh_archive(now_time,broad_array,correct_broadcast);
        
        if($('#player').is('.live')) {
            //the live player is already there
            //so it should play the new broadcast on its own
            //no need to change player
            mylog('the live player is already there');
            return;
        }
        
        //change player??
        change_to_live_or_not();
    }else if(correct_broadcast == false && $('#archive a').is('.active')){
        //no broadcast now and there's an active link 
        //of previous live broadcast
        
        mylog('END of BROADCAST');
        
        //change current broadcast to none
        set_current_broadcast('');
        
        var active_id = $('#archive a.active').attr("id");
        var pending_item = $('#'+active_id);
        pending_item.addClass('pending');
        pending_item.removeClass('active');
        
        //do the same for the span
        var broadcast_hour = active_id.substr(0,2)+':'+active_id.substr(2,2);
        pending_span = $("#sp"+active_id);
        pending_span.html(broadcast_hour);
        pending_span.addClass('pending');
        pending_span.removeClass('active');
        
        //reload archive
        refresh_archive(now_time,broad_array,correct_broadcast);
    }else{
        mylog('just refreshing archive..');
        refresh_archive(now_time,broad_array,correct_broadcast);
    }

    
}

//PRIVATE METHODS

//fetches list of available archives in ftp
//called every cache_archives_for
function get_available_archives_akamai()
{
    //check cache
    now_tmstp = toTimestamp(today+' '+get_now_time()+':00');
    var last_checked = toTimestamp(today+' '+archives_last_fetched+':00');
    if((now_tmstp - last_checked) < cache_archives_for){
        mylog('archive cache is fresh :): ('+now_tmstp+' - '+last_checked +')<'+cache_archives_for);
        return;
    }else{
        //stale cache: re-fetch from server
        var theddate = ddate.replace(/ /g,'');
        theddate = theddate.substr(6,2)+theddate.substr(4,2)+theddate.substr(0,4)//dmy
        var url = "tools.php?day="+theddate;
        mylog('checking archive from url:'+url);
        $.getJSON(url, function(data){
            available_archives = data;
            archives_last_fetched = get_now_time();
        });

    }
    
}

function live()
{
    if(akamai == true){
        //akamai
       
	   AC_FL_RunContent(
            'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',
            'width', '520',
            'height', '330',
            'src', 'AkamaiFlashPlayer2',
            'quality', 'high',
            'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
            'align', 'middle',
            'play', 'true',
            'loop', 'true',
            'scale', 'showall',
            'wmode', 'window',
            'devicefont', 'false',
            'id', 'myPlayer',
            'bgcolor', '#000',
            'name', 'myPlayer',
            'menu', 'true',
            'allowScriptAccess','sameDomain',
			'allowFullScreen', 'true',
            'movie', 'AkamaiFlashPlayer2',
            'FlashVars', 'src=http%3A//tv.economico.pt/economico.smil&amp;autostart=true&amp;themeColor=CCCCCC&amp;mode=sidebyside&amp;scaleMode=native&amp;frameColor=333333&amp;fontColor=cccccc&amp;width=512&amp;link=&amp;embed=',
            'salign', ''        
            ); //end AC code  
     
        mylog('loaded akamai live');
    }else{
        var player = '<div id="myPlayerGoesHere" ><iframe src="http://www.truetech.com.br/webcast/playerWide/interface_silverlight_wide.html" frameborder="0" scrolling="no" width="512px" height="348px" id="iframe_truetech"></iframe></div>';
        mylog('loaded truetech live');
		
    }
    
     var theplayerdiv = $("#player");
     theplayerdiv.removeClass();
     theplayerdiv.addClass('live');
     theplayerdiv.html(player);
     
     //change header
     $("#header_text").html('LIVE STREAMING');
     $("#see_live").removeClass('active');
     $("#see_live").addClass('inactive');
     
     //remove viewings
     if($('#archive a').is('.viewing')) {
        $('#archive a.viewing').removeClass('viewing');
     }
     
     set_next_show();
     
     mylog('changed player to live');
}




function onSilverlightError(sender, args) {

    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }
    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;
    
    var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";
    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";
    
    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
        	errMsg += "Line: " + args.lineNumber + "     \n";
        	errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }
    
    //document.getElementById('silverlightControlHost').innerHTML = errMsg;
    mylog(errMsg);
    //throw new Error(errMsg);
}

function archive_akamai(vid_url)
{
    AC_FL_RunContent(
            'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',
            'width', '520',
            'height', '330',
            'src', 'AkamaiFlashPlayer2',
            'quality', 'high',
            'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
            'align', 'middle',
            'play', 'true',
            'loop', 'true',
            'scale', 'showall',
            'wmode', 'window',
            'devicefont', 'false',
            'id', 'myPlayer',
            'bgcolor', '#000',
            'name', 'myPlayer',
            'menu', 'true',
            'allowScriptAccess','sameDomain',
			'allowFullScreen', 'true',
            'movie', 'AkamaiFlashPlayer2',
            'FlashVars', 'src='+ vid_url + '&amp;autostart=true&amp;themeColor=CCCCCC&amp;mode=sidebyside&amp;scaleMode=native&amp;frameColor=333333&amp;fontColor=cccccc&amp;width=512&amp;link=&amp;embed=',
            'salign', ''        
            ); //end AC code
    mylog('loaded akamai archive: '+vid_url);
}

function archive_sapo(vid_url){
	var vid_id = vid_url.match(/http:\/\/videos\.sapo\.pt\/([a-zA-Z0-9]+)/)[1];
	$('#myPlayerGoesHere').html('\n\
		<object type="application/x-shockwave-flash" data="http://imgs.sapo.pt/sapovideo/swf/flvplayer.swf?v8" width="520" height="330" id="playerSapoFLV" style="visibility: visible;">\n\
			<param name="allowscriptaccess" value="always">\n\
			<param name="allowfullscreen" value="true">\n\
			<param name="wmode" value="opaque">\n\
			<param name="flashvars" value="file=http://rd3.videos.sapo.pt/'+vid_id+'/mov/1">\n\
		</object>\n\
	');
  mylog('loaded sapo video: '+vid_url);
}

/**
* Shows a show from the any place
* @param string vid (akamai -> url, truetech->id)
*/
function simpleview(vid, title, desc)
{
    //clear html        
    var theplayerdiv = $("#player");
    theplayerdiv.html('');
    
    //create replaceable div
    var frag = document.createElement('div');
    frag.id = 'myPlayerGoesHere';
    theplayerdiv.append(frag);
    
    if(vid.match(/videos\.sapo\.pt/)){
			archive_sapo(vid);
		}else{
			archive_akamai(vid);
    }
    theplayerdiv.removeClass();
    theplayerdiv.addClass('archive');
            
    //remove class viewing from all links in div
    $('#archive a').removeClass('viewing');
    
    //change header
    $("#header_text").show().html(title);
    $("#video_title").show().html(title);
    $("#video_title0").html('Info');
    $("#show_image").show();
    
    //change desc
    $("#video_desc").html(desc);
            
    $("#see_live").removeClass('inactive');
    $("#see_live").addClass('active');
    
    mylog('changed player to especial: '+title);
    //scroll(0,0);
		
		$('html, body').animate({
				scrollTop: ($("#content").offset().top - 100)
		}, 2000);
		
    return false; 
}

/**
* Shows a show from the archive
* @param string vid (akamai -> url, truetech->id)
* @param string elem_id eg 1200
*/
function archive(vid, elem_id)
{
    var thearchive = $('#'+elem_id);
    //check if active
    if(thearchive.is('.active')) { 
        live();
    }else if(thearchive.is('.available')) { 
        //available
        //clear html        
        var theplayerdiv = $("#player");
        theplayerdiv.html('');
        
        //create replaceable div
        var frag = document.createElement('div');
        frag.id = 'myPlayerGoesHere';
        theplayerdiv.append(frag);
        
        
        archive_akamai(vid);
        
        theplayerdiv.removeClass();
        theplayerdiv.addClass('archive');
                
        //remove class viewing from all links in div
        $('#archive a').removeClass('viewing');
        thearchive.addClass('viewing');
        
        //change header
        var h = elem_id.substr(2,2);
        if(h > 12){
            var hour_str = h - 12;
            if(h == 13){
                $("#header_text").html('EDI&Ccedil;&Atilde;O DA '+hour_str);
            }else{
                $("#header_text").html('EDI&Ccedil;&Atilde;O DAS '+hour_str);
            }
            
        }else{
            var hour_str = h;
            $("#header_text").html('EDI&Ccedil;&Atilde;O DAS '+h);
        }
        
        //change desc
        $("#video_desc").html($("#sm"+h).html());
                
        $("#see_live").removeClass('inactive');
        $("#see_live").addClass('active');
        $("#video_title0").html('Info');
        $("#show_image").show();
        
        mylog('changed player to archive: '+elem_id);
    

    }  else {
        alert('Emissão ainda não disponível');
    }
    
    return false; 
}

//alert(toTimestamp('2009 02 13 23:31:30'));
//return nr seconds since Jan 01 1970
function toTimestamp(strDate){
    //mylog('generating timestamp of '+ strDate);
    
    //http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript
    
    var datum = new Date(strDate.substr(0,4), strDate.substr(5,2), strDate.substr(8,2), strDate.substr(11,2), strDate.substr(14,2));
    datum = datum.getTime();
    return (datum/1000);
}

//return current hour/minute
//eg. 22:15
function thetime()
{
    //set before time
    $('#before').html($('#now').html());
    
    //hack temp since were now compensating
    //time diffs btw server & client
    use_browser_time=true;
    if(use_browser_time){
        //from client or server
        var now = get_client_time();
        mylog('using browser time');
    }else{
        //get hour from server
        mylog('hour from server');
                
        var now = get_server_time();
    }
        
    //set now time
    $('#now').html(now);
    $('#current_time_display').html(now);
    
    mylog('changed time');
    
    return now;
}

//return 17:34
function get_before_time()
{
    return $('#before').html();
}

function get_now_time()
{
    var hours = $('#now').html();
    hours = String(hours);
    if(hours == 'NaN:NaN'){
        hours = get_client_time();
        hours = String(hours);
    }
    return hours;
}

function get_server_time()
{
    $.get(base_url+'webtv/time.php', function(data) {
        return data;
    });
}


//here

//return current hour/minute
//from browser
//eg. 22:15
function get_client_time()
{
    var currentDate = new Date();
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var btime = (hours<10 ? '0'+hours : hours) + ':'+(minutes<10 ? '0'+minutes : minutes);
    
    if(timediff != 0){
        //compensate timediff
        var month = parseInt(currentDate.getMonth()+1);
        month = (month<10 ? '0'+month : month);
    
        var day = parseInt(currentDate.getDate());
        day = (day<10 ? '0'+day : day);
        var brtoday =  currentDate.getFullYear()+' '+month+' '+day;
    
        //timestamp 
        var br_tmst = toTimestamp(brtoday+' '+btime);
        var compensated_br_tmst = br_tmst + timediff;
        
        btime = get_client_time_from_timestamp(compensated_br_tmst);
    }
    
    $('#browser_hour').html(btime);

    return btime;
}

function get_client_time_from_timestamp(timestamp)
{
    var currentDate = new Date(timestamp * 1000);
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var btime = hours<10 ? '0'+hours : hours;
    btime = btime + ':'+(minutes<10 ? '0'+minutes : minutes);
    
    return btime;
}

function should_reload()
{
    //note: this value must be the same as server
    madrugada = '09:00';
    madrugada_tmstp = toTimestamp(today+' '+madrugada+':00');
    
    bfore = get_before_time();
    bfore_tmstp = toTimestamp(today+' '+bfore+':00');
    
    var now = get_now_time();//17:36
    now_tmstp = toTimestamp(today+' '+now+':00');
                
    //compare timestamps
    
    if(bfore_tmstp < madrugada_tmstp && now_tmstp >=madrugada_tmstp){
        //if in the transition from 7 to 8
        //reload page so that list is regenerated
        //w/ right date values in files
        mylog('bfore:'+bfore + ' now'+now+' REFRESH');
        return true;
    }else{
        return false;
    }
}

//return string 17:00, 16:30
function get_current_broadcast()
{
    var cb = $('#current_broadcast').html();
    return String(cb);
}


//return string 17:00, 16:30 547
function set_current_broadcast(hour)
{
    $('#current_broadcast').html(hour);
    return true;
}

/*
* @param dtime 17:36
* @return string (ex.1700) or false (if not live broadcast now)
*/
function get_broadcast_of_hourminute(dtime, broad_array)
{
    //toTimestamp('2009 02 13 23:31:30')
    //ddate = '2010 02 13'    
    var sd = today + ' ' + dtime;
    d_tmstp = toTimestamp(sd);
    mylog('getting broadcast of '+dtime+' tmst'+d_tmstp);
    
    var i = 0;
    for(keyVar in broad_array)   {
        //mylog('keyVar: '+keyVar);
        var key = parseInt(keyVar);
        var broadcast = String(broad_array[key]);//1700
        var broadcast_hour = broadcast.substr(0,2)+':'+broadcast.substr(2,2);
        var b_tmstp = toTimestamp(today+' '+broadcast_hour);
        //mylog('broadcast: '+broadcast +' tmst.'+b_tmstp);
        
        //get end of broadcast eg 17:00-17:10
        var broadcast_hour_end = broadcast.substr(0,2)+':'+(parseInt(broadcast.substr(2,2))+broadcast_duration_mins);
        var b_tmstp_end = toTimestamp(today+' '+broadcast_hour_end);
        //mylog('broadcast end: '+broadcast_hour_end +' tmst.'+b_tmstp_end);
        
        //next
        var next_i = parseInt(key+1);
        //mylog('next_i: '+next_i);
        
        if(d_tmstp >= b_tmstp && d_tmstp < b_tmstp_end){
            return broadcast_hour;
        }
        
        i++;
    }
    //no live broadcast
    return false;
}
//18:10, array, 18:00
function refresh_archive(dtime,broad_array,new_broadcast)
{
    d_tmstp = toTimestamp(today+' '+dtime+':00');
    
    get_available_archives_akamai();
    
    var viewing_id = '';
    if($('#archive a').is('.viewing')==true) {
        viewing_id = $('#archive a.viewing').attr('id');
        viewing_id = String(viewing_id);
    }
    
    for(keyVar in broad_array)   {
        var key = parseInt(keyVar);
        cssclass='';
        
        var broadcast = String(broad_array[key]);//1700
        var broadcast_hour = broadcast.substr(0,2)+':'+broadcast.substr(2,2);
        var b_tmstp = toTimestamp(today+' '+broadcast_hour+':00');
        
        //get end of broadcast eg 17:00-17:10
        var broadcast_hour_end = broadcast.substr(0,2)+':'+(parseInt(broadcast.substr(2,2))+broadcast_duration_mins);
        var b_tmstp_end = toTimestamp(today+' '+broadcast_hour_end);
        mylog('broadcast end: '+broadcast_hour_end +' tmst.'+b_tmstp_end);
        
        var h_id = '#'+broadcast;
        var item = $(h_id) ;
        var item_span = $('#sp'+broadcast);
        
        item.removeClass();
        item_span.removeClass();
        
        //is it available hackadds 10 mins
        //if(isset('available_archives["'+broadcast+'"]')){
        if(available_archives.hasOwnProperty(broadcast)){
            mylog(broadcast + ' is available');
            cssclass = 'available';
        }else{
            cssclass = 'unavailable';
        }
        
        //is it active
        if(new_broadcast == broadcast_hour && d_tmstp < b_tmstp_end){
            //if active can only be unavailable in archive
            cssclass = 'unavailable active';
            
            //select previous span elem
            item_span.html('EM DIRECTO');

            
        }else{
            cssclass += ' inactive';
            
            item_span.html(broadcast_hour);
        }
        
        item.addClass(cssclass);
        item_span.addClass(cssclass);

    }
    
    if(viewing_id != ''){
        $("#"+viewing_id).addClass('viewing');
    }
}

function change_to_live_or_not()
{
    return;
    //SHOW CONFIRM
    //change to live?
    mylog('ask change to live');
    
    $.sound.play('sounds/PlimShort.mp3', {timeout: 2000});
	var answer = confirm("Está a começar uma emissão em directo. Quer ver?");
	if (answer){ live();};   
}

function mylog(msg)
{
    return;
    try{
        console.log(msg);
    }catch(e){
        return false;
    }
}


var tvguide = null;
function load_todays_tvguide()
{
    
    var url = 'webservices/tvguide/today';
    
    $.getJSON(url, function(data){
            tvguide = data;
            set_next_show();
    });
}

function set_next_show()
{
    if(tvguide===null){
        load_todays_tvguide();
        return true;
    }
    if(tvguide==''){
        $("#video_title0").html("Info");
        $("#video_desc").html('<p><br/>N&atilde;o h&aacute; emiss&atilde;o definida para hoje.</p>');
        $("#show_image").hide();
        $("#video_title").hide();
        return true;
    }
    
    if($("#see_live").hasClass('inactive') == false){
        return true;
    }
    
    var c_now = get_now_time();//ex. 16:21
    var s_now = c_now.replace(':','');
    
    var next_shows = '';
    var k = 1;
    var i = 0;
    var nr_shows_visible = 5;
    for(show in tvguide)   {
    
        var c_hour = tvguide[i].pubdate;
        var show_hour = c_hour.replace(':','');
        
        //next 3 programs
        if(show_hour > s_now && k <= nr_shows_visible){
            var show = '<li><span>'+c_hour.substr(0,5)+ '</span> - ' + tvguide[i].title+'</li>';
            next_shows += show;
            k++;
        }
        i++;
    }
    mylog('next_shows: '+ next_shows);
    if(next_shows !=''){
        var html_next_shows='<ul id="aSeguirList">'+next_shows+'<ul><a href="tvguide"><img src="public/images/verProgramacao.png" class="verProgramacaoBt" /></a>';
        $("#video_title0").html("A seguir");
        $("#video_desc").html(html_next_shows);        
        $("#show_image").hide();
        $("#video_title").hide();
        
    }
    
    
}





