String.prototype.escjqs=function()
{
  a=this.replace(/:/g,"\\:");
  return a;
};


(function(window)
{
  var cp="/w";
  
  var cnb=
  {
    step:0,
    rp:cp,
    prev:
    {
      path:"",
      verb:"",
      arg:""
    },
	current:
    {
      path:"",
      verb:"",
      arg:""
    },
    defaultview:"#home",
    
    load:function(s)
    {
      var parts=s.id.split(":");
      
      var elementid=parts.length>0?parts[0]:null;
      var wrapper=parts.length>1?parts[1]:null;
      var type=parts.length>2?parts[2]:null;
      
      if(elementid==null||wrapper!="content") return;
      
      var target=$("#"+elementid);
      if(target)
      {
        if(__debug__) cnb.util.log("updating target... "+elementid+":"+type);
        if(type==null) target.html(s.innerHTML);
        if(type=="append") target.append(s.innerHTML);
        
        target.css("display",s.style.display);
        $("#"+s.id.escjqs()).remove();
      }
    },

    request:function(path,verb,data)
    {
      if(__debug__) cnb.util.log("requesting... "+path+"|"+verb+"|"+data.arg1);
      this.step++;
      this.current.path=path;
      this.current.verb=verb;
      this.current.arg=data.arg1;
      data.cnb=this;
      cnb.util.showLoader();
	  document.title = "Claps & Boos";
	  $.ajax({
         type:"POST",
         url:cp+"/index.backing.php",
		 data:JSON.stringify(data),
         headers:
         {
           path:path,
           verb:verb
         },
         success:function(responsedata)
         {
           //alert(responsedata);
           if(__debug__) cnb.util.log("reponsedata... "+responsedata);
           cnb.callbacks.clear();
           $("#contentarea").html(responsedata);
           cnb.prev.path=path;
           cnb.prev.verb=verb;
           cnb.prev.arg=data.arg1;
           cnb.util.loadcontentarea();
           cnb.util.hideLoader();
         }
      })
    },

    util:
    {
      loadcontentarea:function()
      {
        if(__debug__) cnb.util.log("updating from contentarea... ");
        $('#contentarea > div').each(function(index,element)
        {
          cnb.load(element);
        });
        cnb.callbacks.invoke();
      },
      log:function(msg)
      {
        if(window.console) console.log(msg);
        else alert(msg);
      },
      cancelEvent:function(evt)
      {
        var e=evt||window.event;

        e.cancelBubble=true;
        e.returnValue=false;

        e.preventDefault && e.preventDefault();
        e.stopPropagation && e.stopPropagation();
      },
      showLoader:function()
      {
        cnb.util.loadertimeid=window.setTimeout("$(\"#loading-indicator\").show();",200);
      },
      hideLoader:function()
      {
        window.clearTimeout(cnb.util.loadertimeid);
        $("#loading-indicator").hide();
      }
    },

    href:function(x,e)
    {
      cnb.util.cancelEvent(e);
      
      if(cnb.context.type=="content")
      {
        if(!x || x=="") hash=cnb.defaultview;
        var parts=x.split("/");
        var form=document.getElementById("form");
        form.path.value=parts[0].substring(1);
        form.verb.value="get";
        if(parts.length>1) form.arg.value=parts[1];
        form.submit();
      }
      else window.location.hash=x;
    },
    navigateto:function()
    {
      var hash=window.location.hash;
      if(!hash || hash=="") hash=cnb.defaultview;
      var parts=hash.split("/");
      cnb.request(parts[0].substring(1),"get",{arg1: parts.length>1?parts[1]:null });
      
      return true;
    },
        
    serializeForm:function(f)
    {
      var a=$(f).serializeArray();
      var o={};
      $.each(a,function()
      {
        if(o[this.name] !== undefined)
        {
          if(!o[this.name].push) o[this.name]=[o[this.name]];
          o[this.name].push(this.value || '');
        }
        else o[this.name] = this.value || '';
      });
      return(JSON.stringify(o));
    },
    
    callbacks:
    {
      functions:[],
      add:function(f)
      {
        this.functions.push(f);
      },
      clear:function()
      {
        this.functions.length=0;
      },
      invoke:function()
      {
        for(var i=0,l=this.functions.length;i<l;i++) this.functions[i]();
      }
    },
    login:
    {
      defaultHandler:function(e)
      {
        cnb.util.cancelEvent(e);
      },
      facebook:function(e)
      {
        cnb.util.cancelEvent(e);
		cnb.href('#login/facebook',e)
		
      },
      google:function(e)
      {
       cnb.util.cancelEvent(e);
	   cnb.href('#login/google',e)
      },
      twitter:function(e)
      {
        cnb.util.cancelEvent(e);
		cnb.href('#login/twitter',e)
      },
      yahoo:function(e)
      {
        cnb.util.cancelEvent(e);
		cnb.href('#login/yahoo',e)
      }
    },
    loggedin:
    {
	  init:function()
	  {
        $(".login").hide();
        $("#loggedin").show();
	  },
      showMenu:function(e)
      {
	    cnb.util.cancelEvent(e);
        var loggedinusermenu=$("#loggedin-user-menu");
        var menucmd=$("#loggedin-user-pic");
        var offset=menucmd.offset();
        loggedinusermenu.css({left:(offset.left-110)+"px",top:(offset.top+40)+"px"});
        loggedinusermenu.show();
        $(document).click(function()
        {
          $("#loggedin-user-menu").hide();
          $(document).click(function(){});
        });
      }
    },
    logout:function(e)
    {
      cnb.util.cancelEvent(e);
      cnb.href('#logout',e);
    },
    initUI:function()
    {
      var loginproviders=$("#login-providers");
      var logincmd=$("#login");
      var offset=logincmd.offset();
      loginproviders.css({left:(offset.left-125)+"px",top:(offset.top+33)+"px"});
      
      $(".lplogo").mouseenter(function()
      {
        $(this).attr("src",cnb.rp+"/images/icons/"+$(this).attr("id")+"-2.png");
      });
      $(".lplogo").mouseleave(function()
      {
        $(this).attr("src",cnb.rp+"/images/icons/"+$(this).attr("id")+"-1.png");
      });
      
      $("#loggedin-user-menu .menuitem").mouseenter(function()
      {
        $(this).removeClass("menuitem-leave").addClass("menuitem-enter");
      });
      $("#loggedin-user-menu .menuitem").mouseleave(function()
      {
        $(this).removeClass("menuitem-enter").addClass("menuitem-leave");
      });
      $("#overlay-wrapper").mousewheel(function(e)
      {
        e.preventDefault();
      });
      $("#overlay-wrapper").mousedown(function(e)
      {
        e.preventDefault();
      });
      
      $("#login").click(function()
      {
        $("#login-providers").show();
        $(document).click(function()
        {
          $("#login-providers").hide();
          $(document).click(function(){});
        });
        return false;
      });
    },
    initSecMenu:function()
    {
      $("#sec-menu a").click(function(e)
      {
        e.preventDefault();
        var position=$(this).position();
        $("#sec-menu .nub").show();
        //$("#sec-menu .nub").css({left:(position.left+($(this).width()/2))+"px"});
        $("#sec-menu .nub").animate({left:(position.left+($(this).width()/2))});
      });
    },
    initHomePage:function(limit)
	{
      $("#spotlight-posters .right-arrow").click(function()
      {
        if(!cnb.posters) cnb.posters={currentId:1};
        
        $("#posters-list-"+cnb.posters.currentId).hide("slide",{direction:"left"},10,function(){
          cnb.posters.currentId++;
          if(cnb.posters.currentId>limit) cnb.posters.currentId=1;
          $("#posters-list-"+cnb.posters.currentId).show("slide",{direction:"right"},300);
        });
      });
      $("#spotlight-posters .left-arrow").click(function()
      {
        if(!cnb.posters) cnb.posters={currentId:1};
        
        $("#posters-list-"+cnb.posters.currentId).hide("slide",{direction:"right"},10,function()
        {
          cnb.posters.currentId--;
          if(cnb.posters.currentId<1) cnb.posters.currentId=limit;
          $("#posters-list-"+cnb.posters.currentId).show("slide",{direction:"left"},300);
        });
      });
      $("#spotlight-posters").mouseenter(function()
      {
        $("#spotlight-posters .right-arrow").show();
        $("#spotlight-posters .left-arrow").show();
      });
      $("#spotlight-posters").mouseleave(function()
      {
        $("#spotlight-posters .right-arrow").hide();
        $("#spotlight-posters .left-arrow").hide();
      });
	},
	dialogs:
    {
      review:
      {
        obj:{},
        initialized:false,
        init:function()
        {
          $("#review-dialog .close-icon").mouseenter(function()
          {
            $(this).attr("src",cnb.rp+"/images/icons/close-2.gif");
          });
          $("#review-dialog .close-icon").mouseleave(function()
          {
            $(this).attr("src",cnb.rp+"/images/icons/close-1.gif");
          });
          
		  var tinymced = new tinymce.Editor('review-input', {
            mode : "textareas",
            theme : "advanced",
            plugins : "emotions",
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|bullist,numlist,|,outdent,indent,|,blockquote,|,anchor,image",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_buttons4 : "",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "",
            theme_advanced_resizing : true,
          });
          tinymced.render();
          //cnb.dialogs.review.editor=tinymced;
          
          $("#review-save").click(function(e)
          {
            e.preventDefault();
			cnb.dialogs.review.hide(e);
            cnb.dialogs.review.save();
          });
          
          $("#review-title").focusin(function()
          {
            var tf=$(this);
            if(tf.attr("value")=="Title..." && tf.hasClass("default-content"))
            {
              tf.attr("value","");
              tf.removeClass("default-content").addClass("content");
            }
          });
          $("#review-title").focusout(function()
          {
            var tf=$(this);
            if(tf.attr("value")=="" && tf.hasClass("content"))
            {
              tf.attr("value","Title...");
              tf.removeClass("content").addClass("default-content");
            }
          });
          //$("#review-save").button();
          cnb.dialogs.review.initialized=true;
        },
        show:function(obj,e)
        {
          cnb.util.cancelEvent(e);
          $("body").css("overflow-y","hidden");
          $("#overlay-wrapper").toggle();
		  $("#review-input").val("");
          $("#review-dialog").toggle();
          var overlayobj=$("#overlay");
          var docobj=$(document);
          overlayobj.offset({top:docobj.scrollTop(),left:0});
          var dialocontentobj=$("#review-dialog-content");
          dialocontentobj.offset({left:(overlayobj.width()-dialocontentobj.width())/2,top:docobj.scrollTop()+(overlayobj.height()-dialocontentobj.height())/2});
          var dialocontentbackobj=$("#review-dialog-content-background");
          dialocontentbackobj.offset({left:(overlayobj.width()-dialocontentbackobj.width())/2+5,top:docobj.scrollTop()+(overlayobj.height()-dialocontentbackobj.height())/2+5});
          if(!cnb.dialogs.review.initialized){ cnb.dialogs.review.init();}
		  else
		  {
		  tinyMCE.activeEditor.setContent('');
		  $("#review-title").attr("value","Title...");
		  $("#review-title").removeClass("content").addClass("default-content");
		  }
		  cnb.dialogs.review.obj=obj;
		  if(cnb.dialogs.review.obj.type == 'review')
		  {
		    $("#review-dialog .editor-type").html("Review for movie - ");
            $("#review-dialog .movie-name").html(obj.moviename);
		  }
		  else if(cnb.dialogs.review.obj.type == 'article')
		  {
		    $("#review-dialog .editor-type").html("Write new Article");
            $("#review-dialog .movie-name").html('');
		  }
        },
        hide:function(e)
        {
          cnb.util.cancelEvent(e);
          $("#review-dialog").toggle();
          $("#overlay-wrapper").toggle();
          $("body").css("overflow-y","auto");
        },
        save:function()
        {
 
		  reviewSaveImpl(cnb.dialogs.review.obj,$("#review-title").attr("value"),tinyMCE.activeEditor.getContent());
        }
      },
      rating:
      {
        obj:{},
        initialized:false,
        init:function()
        {
          $("#rating-dialog .close-icon").mouseenter(function()
          {
            $(this).attr("src",cnb.rp+"/images/icons/close-2.gif");
          });
          $("#rating-dialog .close-icon").mouseleave(function()
          {
            $(this).attr("src",cnb.rp+"/images/icons/close-1.gif");
          });
          $("#rating-save").click(function(e)
          {
            e.preventDefault();
			cnb.dialogs.rating.hide(e);
            cnb.dialogs.rating.save();
          });

          var scrollapi=$("#rating-dialog .list").jScrollPane().data("jsp");
          scrollapi.reinitialise();
          scrollapi.scrollTo(0,192,true);
          
          $("#rating-dialog .item").mouseenter(function()
          {
            $(this).addClass("hilight");
          });
          $("#rating-dialog .item").mouseleave(function()
          {
            $(this).removeClass("hilight");
          });
          $("#rating-dialog .item").click(function(e)
          {
            cnb.dialogs.rating.hide(e);
            cnb.dialogs.rating.save($(this).attr("value"));
          });
          
          cnb.dialogs.rating.initialized=true;
        },
        show:function(obj,e)
        {
          cnb.util.cancelEvent(e);
          $("body").css("overflow-y","hidden");
          $("#overlay-wrapper").toggle();
          $("#rating-dialog").toggle();
          var overlayobj=$("#overlay");
          var docobj=$(document);
          overlayobj.offset({top:docobj.scrollTop(),left:0});
          var dialocontentobj=$("#rating-dialog-content");
          dialocontentobj.offset({left:(overlayobj.width()-dialocontentobj.width())/2,top:docobj.scrollTop()+(overlayobj.height()-dialocontentobj.height())/2});
          var dialocontentbackobj=$("#rating-dialog-content-background");
          dialocontentbackobj.offset({left:(overlayobj.width()-dialocontentbackobj.width())/2+5,top:docobj.scrollTop()+(overlayobj.height()-dialocontentbackobj.height())/2+5});
          if(!cnb.dialogs.rating.initialized) cnb.dialogs.rating.init();
          cnb.dialogs.rating.obj=obj;
          $("#rating-dialog .movie-name").html(obj.moviename);
        },
        hide:function(e)
        {
          cnb.util.cancelEvent(e);
          $("#rating-dialog").toggle();
          $("#overlay-wrapper").toggle();
          $("body").css("overflow-y","auto");
        },
        save:function(r)
        {
          ratingSaveImpl(cnb.dialogs.rating.obj,r);
        }
      }      
    }
  }

  $(document).ready(function()
  {
    $(window).hashchange(cnb.navigateto);
  });

  window.cnb=cnb;

})(window);



//////////// All implementation methods go here ///////////////////////
function reviewSaveImpl(obj,title,Content)
{
  //alert("saving review for movieid " + obj.id+":"+reviewContent);
   if(cnb.dialogs.review.obj.type == 'review')
  cnb.request('review','put',{arg1: obj.id,title: title, content: Content,from:obj.from});
  else if(cnb.dialogs.review.obj.type == 'article')
  cnb.request('article','put',{arg1: '',title: title, content: Content});
}
function ratingSaveImpl(obj,rating)
{
  //alert("saving rating for movieid " + obj.id+":"+rating);
  cnb.request('rate','put',{emo_id: rating,arg1:obj.id,from:obj.from});
}
