// JScript File
    // Templates support
    
    var dialog;
    var htmlDialog;
    
    function ConvertAuthorName(authorName)
    {
        var parts = authorName.split(',');
        if(parts.length<2) return authorName;
        return parts[1]+" " +parts[0];
    }
    
    function BuildQuoteUrl(authorName, authorId, quoteId)
    {
        return "<a href='ByAuthor.aspx?id="+authorId+"&qid="+quoteId+"'>"+ConvertAuthorName(authorName)+"</a>";
    }
    
   function htmlTemplateSaved(tplString)
   {
        templateChangedFromEditor(new AdvancedTemplate(tplString));
   }
    
   function showHtmlDialog()
   {
        if(!htmlDialog) htmlDialog = new HTMLEditorDialog("html-dlg", htmlTemplateSaved);
                 
        htmlDialog.show(userTemplate);
   }
   
   
   function frameLoaded()
   {
        $("div[@id='preloadDiv']").fadeOut("slow");
   }
   
   
   function getPreloadDivCode()
   {
        return '<div id="preloadDiv" style="width:100%;height:100%;left: 0px; position: absolute; top: 0px;background-color:white; text-align:center"><img src="images/ajax-loader.gif" style="position:absolute;top:45%;"/></div>';
   }
    
   function showEditDialog (sender)
   {
        var quoteElement = sender.QuoteControl;        
        currentText = quoteElement.GetText();
        
        //Extract tags
        currentText = quoteElement.RawText;
        var tags = quoteElement.GetTagString();
        
        document.location.href="#"+quoteElement.GetId();
        
        YAHOO.namespace("example.container");
        YAHOO.example.container.editorDialog = new YAHOO.widget.Panel("editorDialog", { width:"700px", visible:true, modal:true, draggable:false, close:true  } );
		YAHOO.example.container.editorDialog.setHeader("?????????????? ??????");
		YAHOO.example.container.editorDialog.setBody('<iframe onload="frameLoaded();" src="Dialogs/EditorWin.aspx?id='+sender.QuoteControl.GetId()+'" style="width:35.50em;height:21.88em;border:0;frameborder:0;overflow:hidden;"></iframe>'+getPreloadDivCode());
		
			
			
		var pnlId = "panel"+sender.QuoteControl.GetId();
		YAHOO.example.container.editorDialog.render(pnlId);
       
       document.EditorDialog =  YAHOO.example.container.editorDialog;
       document.EditorDialog.UpdateQuote =  function(qid, newText, newTags)
       {
            var data = new Array();
            data.Id=qid;
            data.Action='edit';
            data.Data = new Array();
            data.Data.Text = newText;
            data.Data.TagString = newTags;
            document.ActionsFacade.OnItemUpdated(data);
            document.EditorDialog.destroy();
       }
       
   }
   
   function showDialog (sender)
   {
        var quoteElement = sender.QuoteControl;    
        document.ActiveQuote = quoteElement;
        var id = new CookieStorage().GetCookie('activeTpl');
        if(!id) id=1;
        
        document.location.href="#"+quoteElement.GetId();
        
        YAHOO.namespace("example.container");
        YAHOO.example.container.panel2 = new YAHOO.widget.Panel("panel2", { width:"620px", visible:true, modal:false, draggable:false, close:true} );
			YAHOO.example.container.panel2.setHeader("??????????? ??????");
			YAHOO.example.container.panel2.setBody('<iframe onload="frameLoaded();" src="Dialogs/CopyWin.aspx?id='+id+'" style="width:600px;height:350px;border:0;frameborder:0;overflow:hidden;"></iframe>'+getPreloadDivCode());
			//YAHOO.example.container.panel2.setFooter("End of Panel #2");
			var pnlId = "panel"+sender.QuoteControl.GetId();
			YAHOO.example.container.panel2.render(pnlId);
		
	
        return;
             
    }
    
    function ShowLoginDialog()
    {
        YAHOO.namespace("dialogs.modal");
        YAHOO.dialogs.modal.loginDialog = new YAHOO.widget.Panel("loginDialog", { x:300, y:300, width:"350px", fixedcenter: true,  visible:true, modal:true, draggable:false, close:true, iframe:true  } );
		YAHOO.dialogs.modal.loginDialog.setHeader("Login");
		YAHOO.dialogs.modal.loginDialog.setBody($("div[@id='login']").get(0));
		YAHOO.dialogs.modal.loginDialog.render("doc2");
    }
    
    
    $(document).ready(
    function()
    {
   
    // Global initialization.
    document.ActionsFacade = new ActionsFacade();
    
       var isAuth = !new ConfigFacade().IsAnonymous();
           
        $("div.quoteBlock").each(
            function()
        {
           var quoteElement = new QuoteElement(this);
           var ratingWidget = new StarRatingWidget(isAuth);
           quoteElement.AddTopBarWidget(ratingWidget);
           quoteElement.AddTopBarWidget(new TextRatingWidget());
           
           quoteElement.AddBottomBarAction("icons/html.png","???????? ????? ? HTML ???",function(){showDialog(this);});
           
           //Temp solution to determine, if permalink must be shown
           var sPath = window.location.pathname;
           var pageName = sPath.substring(sPath.lastIndexOf('/') + 1);
           
           if("quote.aspx"!=pageName)
           {
                var commentsCount = quoteElement.GetCommentsCount();
                var linksCount = quoteElement.GetLinksCount();
                var id = quoteElement.GetId();
                var commentText = ("0"==commentsCount)? "??? ????????????" : "??????????? ("+commentsCount+")";
                quoteElement.AddBottomBarAction("icons/comment.png","<a style='Color:Gray' rel='prefetch' href='quote.aspx?id="+id+"&view=comments'>"+commentText+"</a>");
                if(linksCount>0)
                {
                    quoteElement.AddBottomBarAction("icons/link.png","<a style='Color:Gray' rel='prefetch'  href='quote.aspx?id="+id+"&view=links'>?????? ("+linksCount+")</a>");    
                }
           }
           if(isAuth)
           {
                quoteElement.AddTopBarWidget(new FavoritesWidget());
                quoteElement.AddTopBarAction("icons/pencil.png","",function(){showEditDialog(this);},"????????????? ??????");
                
           }
           
           this.Control = quoteElement; // Quote element attaches to node and accepts incoming events.
           quoteElement.Render();
        });
        
        
             
       // Load user favorites data
      if(isAuth) document.ActionsFacade.GetFavorites(
        function(response) //Occurs when favorites xml is loaded.
        {
            var data = document.ActionsFacade.GetJsonRequestData(response);
            if(!data) 
            {
                return;
            }
            var favsArray = data.Data[0];
            var quoteControls = new Array();
            // Build quote elements hashtable
            $("div.quoteBlock", document).each(
               function()
                {
                    quoteControls[this.id]=this.Control;
                }
               );
           //Iterate favorites array.
           for(var i=0;i<favsArray.length;i++)
           {
                var curId = favsArray[i];
                var quoteElem = quoteControls[curId];
                if(undefined!=quoteElem)
                {
                    quoteElem.SetWidgetValue(FavoritesWidget.prototype.GetWidgetName(), "1");
                }
           }
      }
      );
      }
    );

// ActionsFacade

ActionsFacade.prototype.interfaceUrl = "data/json.ashx";

function ActionsFacade()
{
}

ActionsFacade.prototype.GetJsonRequestData = function(response)
{ 
    var responseObj = eval("("+response+")");       
    var action = responseObj.Action;
    
    if(responseObj.Status!=1)
    {
     // Error processing must be here.
        var message = responseObj.Message;
        if(!message) message = "Unspecified server error.";
        alert(message);
        return null;
    }
    
     if(responseObj.SGuid!="")
     {
        // Action must have user confirmation.
        ActionsFacade.prototype.TestUser(responseObj.SGuid);
        return null;
     }
     
     return responseObj;
}

// Generates function which overwrites quote id in returning data.
ActionsFacade.prototype.GetStandardJsonHandler = function(qid)
{
    return new Function("response","var data = ActionsFacade.prototype.GetJsonRequestData(response); data.Id="+qid+";ActionsFacade.prototype.OnItemUpdated(data);");
}

ActionsFacade.prototype.SaveQuoteChanges = function(qid, text, comment, tags)
 {
    var jsonCallback = this.GetStandardJsonHandler(qid);
    $.post(this.interfaceUrl+"?id="+qid+"&action=edit",{text:text,tags:tags, comment:comment}, jsonCallback);
 }
  
ActionsFacade.prototype.VoteForQuote = function(qid, value)
{
    var jsonCallback = this.GetStandardJsonHandler(qid);
    $.get(this.interfaceUrl,{id:qid,action:"vote",id:qid,value:value},jsonCallback);
}

ActionsFacade.prototype.SwitchFavorites = function(qid)
{
    //Save current date to special cookie to allow result caching.
    var curDate = new Date ();
    new CookieStorage(document).SetCookie("last_fav",curDate.getTime());
    var jsonCallback = this.GetStandardJsonHandler(qid);
     $.get(this.interfaceUrl,{id:qid,action:"fav"},jsonCallback);
}

ActionsFacade.prototype.GetFavorites = function(handler)
{
    var curDate = new Date ();
    new CookieStorage(document).SetCookie("last_fav",curDate.getTime());
    $.get(this.interfaceUrl,{action:"get_favs"},handler);
}

// Fires when some item on the page must be updated using new data.
ActionsFacade.prototype.OnItemUpdated = function(data)
{
    if(!data) return; // Error must be handled before.
    var qid = data.Id;
    var action = data.Action;
    var target = $("div[@id="+qid+"]").get(0);
    var quoteElement = target.Control;
    if(quoteElement)
    {
        quoteElement.OnNeedUpdate(action, data);
    }
}
// 11.09.2010 2:01:58