TV.Show = {
    arLinkIds : [],
    init:function() {
       $("#read_more").click(TV.Show.moreDescription); 
       $("#add_favorites").live("click",TV.Show.addToFavorites);
       $("#remove_favorites").live("click",TV.Show.removeFromFavorites);
       
       $("#subscribe_show").live("click",TV.Show.subscribe);
       $("#unsubscribe_show").live("click",TV.Show.unsubscribe);
       
       
       $("#episode li.main a.collapsed,#episode li.main a.expand").live("click",TV.Show.seasonInteraction);
     
       $("#load_more_online").click(TV.Show.loadMoreEpisodes);
       
       $("#initial_links .td_report span").live("click",TV.Show.reportLink);
       $("#initial_links .td_report span").hover(function(){
          $(this).addClass("hover"); 
       }, function(){
          $(this).removeClass("hover"); 
       });
       
       // add link
       $("#add_link a").click(TV.Show.addLink);
       $("#close_add_link,#cancel_add_link").live("click",TV.Show.closeAddLink);
       $("#form_add_link").live("submit",TV.Show.saveLink);
       
       // add comment
       $("#form_add_comment").submit(TV.Show.addComment);
       $("div.votes-icons a").live("click",TV.Show.rateLink);
       
       $("a.reply").live("click",TV.Show.reply);
       
       $("#comments_container ul#pager li a").live("click",TV.Show.paginateComments);
       
       $("#cancel_reply_btn").live("click",TV.Show.closeReply);
       $("#form_add_reply").live("submit",TV.Show.addReply);
    },
    addReply : function(){
       var form_valid = true;
      $(".form_error").hide();
      var error = '';
   
      var comment = jQuery.trim($("#reply_ta").val());
      if (comment == '') {
           form_valid = false;
           error += "Please enter your reply <br />";
      }
          
      if (form_valid == true) {
          $("#leave-reply input[type='submit']").hide();
          $.ajax({
                    type     : $(this).attr("method"),
                    url      : $(this).attr("action"),
                    data     : $(this).serialize(),
                    dataType : "json",
                    success  : function(jsonResponse){                       
                       if ( jsonResponse.success == true) {                            
                            TV.notifyMessage(jsonResponse.message);  
                            var el = $("#comment_"+jsonResponse.comment_id).nextUntil(".comment-box").last();
                            if (el.length > 0) {
                                el.after(jsonResponse.commment_html);
                            } else {
                                $("#comment_"+jsonResponse.comment_id).after(jsonResponse.commment_html);
                            }
                           
                            TV.Show.closeReply();
                            
                       } else if ( jsonResponse.success == false) {
                             TV.notifyMessage(jsonResponse.message); 
                       }                  
                    }
            });
               
      } else {
         TV.notifyMessage(error); 
      }
      
      return false;
    },
    closeReply : function(){
        $("#leave-reply").fadeOut("slow",function(){
            $(this).remove();
        });
        return false;
    },
    paginateComments : function(){
       $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    success  : function(htmlResponse){
                        $("#comments_container").fadeOut("slow",function(){
                            $(this).html(htmlResponse).fadeIn("slow");
                        });
                    } 
                    
         }); 
      return false;
    },
    reply : function(){
       var position = $(this).position(); 
       $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    success  : function(htmlResponse){
                          var reply = $(htmlResponse).hide().css({"top":position.top+"px",
                                                                  "left" :Math.round(position.left - 500)+"px"});
                          $("body").append(reply);
                          reply.show();
                    } 
                    
       }); 
       
       return false;
    },
    rateLink : function(){
        $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    dataType : "json",
                    success  : function(jsonResponse){
                        
                        TV.notifyMessage(jsonResponse.message);  
                        if (jsonResponse.success == true) {
                            votes_updated  = jsonResponse.nr_votes;
                           if ( ( votes_updated ==1) || (votes_updated == -1) ) {
                               votes_updated += ' Vote';
                           } else {
                               votes_updated += ' Votes';
                           }
                           
                           $("#votes_"+jsonResponse.link_id).html(votes_updated);
                        } 
                    }
         }); 
      return false;
    },
    putBackground : function(series_id){
        var image_url = TV.base_url+'images/'+series_id+'/original_banner.jpg';
        $('<img />')
        .attr('src', image_url)
        .load(function(){
          $("body").css("background-image","url("+image_url+")" );
        });
    
    },
     addToFavorites : function(){
        $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    dataType : "json",
                    success  : function(jsonResponse){
                        if (jsonResponse.success == false) {
                            TV.notifyMessage(jsonResponse.message);    
                        } else { 
                            $("#add_favorites").attr("href",jsonResponse.remove_favorites_url).attr("id","remove_favorites").text('Cancel favorite');
                            TV.notifyMessage(jsonResponse.message);       
                            
                        }
                    }
         }); 
      return false;
    },
    removeFromFavorites : function(){
       $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    dataType : "json",
                    success  : function(jsonResponse){
                        if (jsonResponse.success == false) {
                                TV.notifyMessage(jsonResponse.message);   
                        } else { 
                            $("#remove_favorites").attr("href",jsonResponse.add_favorites_url).attr("id","add_favorites").text('Add to favorites');
                            TV.notifyMessage(jsonResponse.message);  
                        }
                    }
         });
      return false;
    },
        subscribe : function(){
         $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    dataType : "json",
                    success  : function(jsonResponse){
                        if (jsonResponse.success == false) {
                               TV.notifyMessage(jsonResponse.message);    
                        } else { 
                            $("#subscribe_show").attr("href",jsonResponse.unsubscribe_url).attr("id","unsubscribe_show").text("Unsubscribe");
                            TV.notifyMessage(jsonResponse.message);       
                        }
                    }
         }); 
       return false;
    },
    unsubscribe : function(){
         $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),                    
                    dataType : "json",
                    success  : function(jsonResponse){
                        if (jsonResponse.success == false) {
                                 TV.notifyMessage(jsonResponse.message);  
                        } else { 
                            $("#unsubscribe_show").attr("href",jsonResponse.subscribe_url).attr("id","subscribe_show").text("Subscribe");
                            TV.notifyMessage(jsonResponse.message);  
                        }
                    }
         });
      return false;
    },
    seasonInteraction : function(){
        
        var season_id = $(this).attr('href');
        season_id = season_id.substring(season_id.lastIndexOf("_")+1);
       
        if ($("#season_"+season_id).hasClass("hide")) {
            
            $("ul.show").fadeOut("fast",function(){
                $(this).removeClass("show").addClass("hide");
                
                $("#season_"+season_id).fadeIn("fast",function(){
                    $(this).removeClass("hide").addClass("show");
                });
            });
        }
      
        return false;
    },
    moreDescription : function(){
       
        $.ajax({
                    type     : "GET",
                    url      : $(this).attr("href"),
                    dataType : "json",
                    success  : function(jsonResponse){  
                             $("#full_description").slideUp("slow",function(){
                                $(this).html(jsonResponse.description).slideDown("slow"); 
                            });
                    }
        });
       
        return false;
    },
    addComment : function(){
      
      var form_valid = true;
      $(".form_error").hide();
      var error = '';
   
      var comment = jQuery.trim($("#comment_ta").val());
      if (comment == '') {
           form_valid = false;
           error += "Please enter your comment <br />";
      }
          
      if (form_valid == true) {
          
          $("#form_add_comment input[type='submit']").hide();
          $("#leave-comment").css({opacity: 0.5});
           $.ajax({
                    type     : $(this).attr("method"),
                    url      : $(this).attr("action"),
                    data     : $(this).serialize(),
                    dataType : "json",
                    success  : function(jsonResponse){                       
                       if ( jsonResponse.success == true) {                            
                            TV.notifyMessage(jsonResponse.message);   
                            $("#comments-list").prepend(jsonResponse.commment_html);
                            
                            $("#form_add_comment input[type='submit']").show();
                            $("#leave-comment").css({opacity: 1});
                            
                       } else if ( jsonResponse.success == false) {
                             TV.notifyMessage(jsonResponse.message); 
                       }                  
                    }
            });
               
      } else {
         TV.notifyMessage(error); 
      }
      
      return false;
    },
    getDomain:function(url){
        try {
            return url.match(/:\/\/(www\.)?(.[^/:]+)/)[2];
        } catch (ex){
            return false;
        }
    },
    saveLink : function(){
      var form_valid = true;
      $(".form_error").hide();
      var error = '';
   
      // validate link
      var ck_url =  /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
      var link = jQuery.trim($("#add_link_input").val());
      if (!ck_url.test(link)) {
           form_valid = false;
           if ($(".errors_div").css("display") == "none") {$(".errors_div").show();}
           error += "&bull;&nbsp;&nbsp; Please specify a valid link <br />";
      }
      
      var domain = TV.Show.getDomain(link);
      if (jQuery.inArray(domain, TV.Show.allowedSites)==-1){
          form_valid = false;
          if ($(".errors_div").css("display") == "none") {$(".errors_div").show();}
          error += "&bull;&nbsp;&nbsp; Source not supported <br />";
      }
       
      if (form_valid == true) {
          
           $.ajax({
                    type     : $(this).attr("method"),
                    url      : $(this).attr("action"),
                    data     : $(this).serialize(),
                    dataType : "json",
                    success  : function(jsonResponse){    
                        
                       if ( jsonResponse.success == true) {
                            TV.Show.closeAddLink();
                            $("#no_links_yet").fadeOut("slow");
                            TV.notifyMessage(jsonResponse.message);                            
                            $("#results-list ul").prepend(jsonResponse.link_html);
                            $("#results-list ul li:first").fadeIn("slow");
                            TV.Show.arLinkIds.push(jsonResponse.link_id);
                       } else {
                             $("#form_add_link .errors_div").show();
                             $("#error_add_link").html(jsonResponse.message).show("slow");
                             
                       }                  
                    }
            });
               
      } else {
          $("#form_add_link .errors_div").show();
          $("#error_add_link").html(error).show("slow");
      }
      
      return false;
    },
    closeAddLink : function(){
        
         $("#popup_container_add_link").hide("fast",function(){
             TV.hideOverlay();
             $(this).remove();
        });
        TV.popupAddLink = false;     
        return false;
    },
    addLink : function(){
        $('html,body').animate({scrollTop: 0}, 100);
        
      TV.showOverlay();
      if (TV.popupAddLink == false) {
          var href = $(this).attr("href");
          var dialog = $('<div id="popup_container_add_link" style="display:none;"></div>').appendTo('body');   

          dialog.load(
                    href,
                    {},
                    function (htmlResponse, textStatus, XMLHttpRequest) {
                        if (htmlResponse == 'false') {
                            TV.hideOverlay();
                            TV.notifyMessage("Please login in order to perform this action!");
                        } else {
                            $("#popup_container_add_link").html(htmlResponse).show("fast");
                            
                        }
                        TV.popupAddLink = true;
                       
                    });
      }
      
      return false;
    },
    reportLink : function(){
      var tr = $(this).parents("tr");
      link_id = $(this).attr("id").substring(7);
      $.ajax({
                    type     : "GET",
                    url      : TV.base_url+'report_link/'+link_id,                    
                    dataType : "json",
                    success  : function(jsonResponse){
                        if (jsonResponse.success == true) {
                            tr.fadeOut("slow",function(){
                                tr.remove();
                            });
                            TV.notifyMessage(jsonResponse.message);       
                        }
                    }
         }); 
      return false;
    },
    loadMoreEpisodes : function(){
      var episode_id = $("#episode_id").val(); 
      
      var current_index = parseInt( $("#current_index").val() );
      var more_nr_link =  parseInt(  TV.Show.more_nr_links )
      current_index += more_nr_link;
      
     
      /*
      if ( (current_index + TV.Show.more_nr_links ) >   TV.Show.nr_links  )  {
        $("#load-more").fadeOut("slow");
      }
      */
     
      var allready_added_links = '';
      if ( TV.Show.arLinkIds.length > 0 ) {
          allready_added_links += '/'+TV.Show.arLinkIds.join('.');
      }
      $.ajax({
                    type     : "GET",
                    url      : TV.base_url+'episode/more/'+episode_id+'/'+current_index+allready_added_links,  
                    success  : function(htmlResponse){
                        if (htmlResponse!=''){
                            var response = $(htmlResponse).hide();
                            $("#load-more").before(response);
                            response.slideDown("slow");
                            $("#current_index").val(current_index);
                        } else {
                             $("#load-more").fadeOut("slow");
                        }
                    }
      }); 
      return false;
      
    },

    visit:function(series){
         $.ajax({
                    type     : "POST",
                    url      : TV.base_url+'show/visit',
                    data     : {series_id:series}
         });
    }
};

$(document).ready(TV.Show.init);
