﻿//all the data of the month
var month_data = null;
// time to manipulate the calendar shit
var time = new Time();
var diary_day = 0; 
 
function skipWeek(val)
{
	if(month_data == null)
	{
		getData(val);
	}
	
	var current_month = time.month();

	time = new Time(time.year(), time.month(), time.day()+(7-time.weekday())+val);
	if(time.month() != current_month)
	{	
		getData(val);
	}
	else
		fillHtml();
	
	return false;
}
 
 
function skipMonth(val)
{
 
        if(month_data == null)
        {
                getData(val);
        }      
        time = (val>0)? time.nextMonth():time.previousMonth();
 
        getData(val);
        return false;
}
 
function getData(val)
{  
        //Calculate the size + position of the modal
        $("#monthModal").html('<center><img src="/static/images/site/ajax-loader.gif" style="margin-top:10px;" /></center>')
        .width($(".weekBottom").width())
        .height($(".weekBottom").height()*$(".weekBottom").length)
        .css("margin-top",$(".weekBottom").css("margin-top"))
        .css("top",$(".weekBottom").position().top)
        .css("left",$(".weekBottom").position().left)
        .fadeTo('fast',0.7);
       
	  	var tmp_date = (val>0)? new Time(time.clone().endOfWeek().year(),time.clone().endOfWeek().month(),time.clone().endOfWeek().day()):new Time(time.clone().beginningOfMonth().year(),time.clone().beginningOfMonth().month(),time.clone().beginningOfMonth().day());
		var get_month = (tmp_date.month()!= time.month())? tmp_date.month():time.month();
		var get_year = (tmp_date.month()!= time.month())? tmp_date.year():time.year();
       
	    if(public_cal == 0)
        {    
            var req_url = '/'+site_lang+'/subscenter/cal-week/get/';
            var params = {month:get_month, year:get_year}
        }
        else
        {
                var req_url = '/'+site_lang+'/subscenter/cal-def/get/'+get_month+'/'+get_year+'/';
                var params = {}                        
        }
       
        $.getJSON(req_url,params, function(data) {                                                                                       
                month_data = data;
                fillHtml();                
        $("#refreshcal").html('');
                $("#monthModal").fadeOut();
        });
   
}
 
function fillHtml()
{
        //Count how many divs there is to deremine if its week or not
        if($(".day").length > 7)
        {
                //First day of the week
                var tmp_time = new Time(time.beginningOfMonth().year(),time.beginningOfMonth().month(),time.beginningOfMonth().day());
                tmp_time = tmp_time.advanceDays(-tmp_time.weekday()+1);
                time = tmp_time.clone().advanceDays(6);
				
				//Hide the extra week
				if(time.weeksInMonth()<6)
					$(".weekBottom:last").hide();
				else
					$(".weekBottom:last").show();
        }
        else
        {
                //First day of the week
                var tmp_time = new Time(time.beginningOfWeek().year(),time.beginningOfWeek().month(),time.beginningOfWeek().day());
                time = tmp_time.clone().advanceDays(6);
        }
       
    var main_link;                    
    var season_link;
    var episode_link;
    var subtitle_icon;                        
    var el;
    var line_el;
   
        //reset all the fields
        $(".dayExpandBtn").remove();
        $(".dayBottomContent").css({overflow:'hidden', height:145});
       
        $(".dayBottomContent").each(function(index){
                if(index>0)
                        tmp_time = tmp_time.advanceDays(1);
               
                //Mark the today class
                var today = new Time();
                if(today.day() == tmp_time.day() && today.month() == tmp_time.month() && today.year() == tmp_time.year())
                {                       	         	
						diary_day=index+1;
						// set_diary_day for pluggin  
						if(window.set_diary_day)
							set_diary_day();
						
                        var class_name = (today.weekday()==1)? 'todayFirst':'today';
                        class_name = (today.weekday()==7)? 'todayLast':class_name;
                        $(this).parent().parent(".day").addClass(class_name);
                }
                else
                        $(this).parent().parent(".day").removeClass("today todayFirst todayLast");
               
                var date = zeroLeading(tmp_time.day())+'.'+zeroLeading(tmp_time.month())+'.'+tmp_time.year();
                //change the dates
                $(this).empty();
                $(this).append('<div class="weekDate">'+date+'</div>');
               
                //if there is data to that date
                if('d'+date.replace(/\./g,'') in month_data)
                {                            
                        var obj = month_data['d'+date.replace(/\./g,'')];
                        var container = $(this);
                        line_el = 0;
                        for (i in obj)
                        {
             
                if(obj[i].subtitle == 1)
                {
                    subtitle_icon = '<img src="/static/images/site/videoLink.png" alt="" />';
                }
                else
                {
                    subtitle_icon = '';
                }
               
                 
                             
                                if(obj[i].type=='1')
                {            
                 
                 
                    main_link = "/"+site_lang+"/subtitle/series/"+obj[i].links.main;                    
                    season_link = main_link+"/#"+obj[i].links.season;
                    episode_link = main_link+"/"+obj[i].links.season+"/"+obj[i].links.episode;
                                       
                                                           
                                        el = $('<div class="weekSeries" style="display:none;">'
                                                                                +'<a href="'+main_link+'" class="weekSeriesTitle">'+subtitle_icon +'<span class="linkNearImgs">'+obj[i].title.main+'</span></a>'
                                                                                +'<a href="'+season_link+'" class="weekSeriesSE">'+gettext('Season')+" "+obj[i].title.season+'</a>, '
                                                                                +'<a href="'+episode_link+'" class="weekSeriesSE">'+gettext('Episode')+" "+obj[i].title.episode+'</a>'
                                                                        +'</div>');
                                   
                    container.append(el);                                    
                                   
                }
               
                                if(obj[i].type=='2')
                {
                 
 
                    main_link = "/"+site_lang+"/subtitle/movie/"+obj[i].links.main;        
                    season_link = ""
                    episode_link = ""
                               
                                        el = $('<div class="weekSeries" style="display:none;"><a href="'+main_link+'" class="weekSeriesTitle weekSeriesMovieTitle">'+subtitle_icon +'<span class="linkNearImgs">'+obj[i].title.main+'</span></a></div>')
                    container.append(el);
                         
                }
                               
                $(".weekSeries").show();                                                       
                                //$(".weekSeries").slideDown("fast");
                        }                              
                        //if the content is overflow show the more content
                        if(this.scrollHeight>145 && $(this).parent().find(".dayExpandBtn").length==0)
                        {      
                                $(this).parent().append('<a class="dayExpandBtn" href="#" onclick="return showHide(this);"><span class="dayExpandBtnContent">'+gettext('Show all')+'</span></a>');
                        }
                }
                else if($(this).find('.noSeries').length==0)
                {
                        $(this).append('<span class="noSeries">'+gettext('No broadcast TV and movies')+'</span>');
                }
        });  
        
}
 
function zeroLeading(num)
{
        if(num<10)
                num = "0"+num;
        return num;
}
 
 
function showHide(obj)
{    
    //Get the max hight
    var maxHeight = 0;
    $(".dayBottomContent").each(function(index){
        if(maxHeight<$(this).height() && $(this).css('overflow') == 'visible')
            maxHeight = $(this).height();
    });
   
    var content = $(obj).parent(".dayBottom").find(".dayBottomContent");
    if(content.css('overflow') == 'hidden')
    {
        var currentHeight = content.get(0).scrollHeight;
        currentHeight = (maxHeight<currentHeight)? currentHeight:maxHeight;
       
        if(currentHeight>maxHeight)
        {
            $(".dayBottomContent").each(function(index){
                if($(this).css('overflow') == 'visible')
                    $(this).animate({ height: currentHeight });
            });
        }
       
        content.css({overflow:'visible'}).animate({ height: currentHeight });
        $(obj).find(".dayExpandBtnContent").text(gettext('Close'));
    }
    else
    {
        content.css({overflow:'hidden'}).animate({ height: '145' });
        $(obj).find(".dayExpandBtnContent").text(gettext('Show all'));
    }
   
    return false;
}
 
function showAll()
{
    $(".dayExpandBtn").trigger("click");
    return false;
}
