$(function()
{
   $('#aPostComment').click(function()
   {
      if ($('#commentadd').is(':visible')) $('#commentadd').hide();
      else $('#commentadd').show();
      
      return false;
   });
   
   if (location.hash=='#postcomm')
   {
      $('#commentadd').show();
   }
   
   // load comments
   function loadComments(page)
   {
      if (page==null) page=0;
      
      $('#loading').css('top',
         $('#main').offset()['top']
            +($('#main').offset()['height']/2)
            -30);
      $('#loading').css('left',
         $('#main').offset()['left']
            +($('#main').offset()['width']/2)
            -120);     
      $('#loading').show();
      // refresh comments list
      $.get(tgSitesUri+'/site/getcommajax/'+$('#siteid').val()+'/'+page+'/',
         function(result,text)
         {
			$('#main').html(text)
				.find('a.aPostReply').bind('click',aPostReply_click).end()
           		.find('a.aDeleteComment').bind('click',aDeleteComment_click).end()
            	.find('a.aEditComment').bind('click',aEditComment_click).end()
            	.find('a.aFRPostReply').bind('click',aFRPostReply_click).end() 
            	.find('a.aEditReply').bind('click',aEditReply_click).end()
            	.find('a.aRepReportAdmin').bind('click',aRepReportAdmin_click).end() 
            	.find('a.aReportAdmin').bind('click',aReportAdmin_click).end()            	
            	.find('a.aDeleteReply').bind('click',aDeleteReply_click).end();             
            $('#commentspages').html(result.commpagin)
               .find('a.aPagin').bind('click',aPagin_Click);
            $('#loading').hide();
            $('a.aPagin').css('font-weight','normal');
            $('a.aPagin[@name="'+page+'"]').css('font-weight','bold');
         });
   }
   
   // load focuses
   function loadFocuses(page)
   {
      if (page==null) page=0;
      $('#loading').css('top',
         $('#sfocuseslist').offset()['top']
            +($('#sfocuseslist').offset()['height']/2)
            -30);
      $('#loading').css('left',
         $('#sfocuseslist').offset()['left']
            +($('#sfocuseslist').offset()['width']/2)
            -120);
      $('#loading').show();
      // refresh focuses list
      $.get(tgSitesUri+'/site/getfocusajax/'+$('#siteid').val()+'/'+page+'/',
         function(result,text)
         {
            $('#sfocuseslist').html(text)
               .find('td.focrate div.fon').bind('mousemove',div_fonHover);
            $('#sfocuseslist div.fon img').bind('mouseout',div_fonImgOut);
            $('#sfocuseslist div.fon img').bind('click',div_fonImgClick);
            $('#sfocusespages').html(result.sfocpagin)
               .find('a.aFocPagin').bind('click',aFocPagin_Click);
            $('#loading').hide();
            $('a.aFocPagin').css('font-weight','normal');
            $('a.aFocPagin[@name="'+page+'"]').css('font-weight','bold');
         });
   }
   // focus pagin link
   var aFocPagin_Click=function()
   {
      loadFocuses($(this).attr('name'));
      return false;
   };
   $('a.aFocPagin').bind('click',aFocPagin_Click);
   $('a.aFocPagin').focus(function(){this.blur();});
   
   // comment length
   if ($('#comment').is('textarea'))
   {
      var checkCommentLength=function()
      {
         var val=$('#comment').val();
         if (val.length>1000) $('#comment').val(val.substring(0,1000));
         else
         {
            val=1000-val.length;
            $('#commln').html(val?val:'0');
         }
      };
      $('#comment').bind('keyup',checkCommentLength);
      checkCommentLength();
   
      // comment submitting
      var comm_form_submit=function()
      {
         validateForm('#commentform');
         
         if (formErrors._count>0)
         {
            // show error
            showFormError('#commentform');
         }
         else
         {
            $.post(tgSitesUri+'/site/savecommajax/',
               {q:$('#commentform')[0]},
               function(result,text)
               {
                  if (parseInt(text)>0)
                  {
                     loadComments();                     
                     $('#commentadd').hide();
                     $('#comment').val('');
                     var val=$('#comment').val();
                     $('#commln').html(val?val:'1000');                 
                  }
                  else if (text=='0')
                     showFormErrorString('#commentform',result.error);
                  else
                     showFormErrorString('#commentform','Comment has not been added. Please, try again.');

                  $('#comment_text').bind('submit',comm_form_submit);
               });
         }
         return false;
      };
      $('#commentform').bind('submit',comm_form_submit);
   }
   
   // pagin link
   var aPagin_Click=function()
   {
      loadComments($(this).attr('name'));
      return false;
   };
   $('a.aPagin').bind('click',aPagin_Click);
   $('a.aPagin').focus(function(){this.blur();});
   
   
   // RATING
   // HOVER
   var div_fonHover=function(e)
   {
      var evt=$.event.fix(e);
      var mL=evt.pageX-$(this).offset()['left'];
      mL=Math.ceil(mL/21);
      
      $(this).find('img').each(function()
      {
         if ($(this).attr('alt')<=mL) $(this).css('display','inline');
         else $(this).hide();
      });
   };
   $('td.focrate div.fon').bind('mousemove',div_fonHover);
   var div_fonImgOut=function()
   {
      $(this).parent().find('img').hide();
   };
   $('td.focrate div.fon img').bind('mouseout',div_fonImgOut);
   
   // CLICK
   var div_fonImgClick=function()
   {
      $('#loading').css('top',
         $('#focustab').offset()['top']
            +($('#focustab').offset()['height']/2)
            -30);
      $('#loading').css('left',
         $('#focustab').offset()['left']
            +($('#focustab').offset()['width']/2)
            -120);
      $('#loading').html('Please wait...');
      $('#loading').show();
      if ($(this)[0].className=='donut')
         var ph=$(this).parent().next('td');
      else
         var ph=$(this).parent().parent();
      
      var gamfoc=ph.attr('name');
      var rate=gamfoc+'_'+$(this).attr('alt');
      
      // refresh ratings list
      $.get(tgSitesUri+'/site/rateajax/'+$('#siteid').val()+'/'+rate+'/',
         function(result,text)
         {
            if (text=='1')
            {
               // redraw Overall rating
               var orate=result.sitesum/result.sitecount;
               var rw=orate*30;
               if (orate>0)
               {
                  var rmin=Math.floor(orate);
                  if (orate>rmin) rw=Math.ceil(rmin*30+25*(orate-rmin)+3);
               }
               $('#orate').css('width',rw+'px');
               
               // redraw this focus rating
               orate=result.focussum/result.focuscount;
               rw=orate*21-4;
               if (orate>0)
               {
                  var rmin=Math.floor(orate);
                  if (orate>rmin) rw=Math.ceil(rmin*21+16*(orate-rmin));
               }
               ph.find('div.frate').css('width',rw+'px');
               ph.attr('class','');
               ph.attr('id','');
               ph.attr('name','');
               ph.find('div.fon').remove();
               ph.prev('td').find('img')[0].src='/res/im/r/donut0.gif';
               var newRate=Math.round(orate*10)/10;
               if (newRate.toString().indexOf('.')==-1) newRate=newRate.toString()+'.0';
               ph.next('td').find('.fratev').html(newRate);
               
               // redrae game rating
               orate=result.gamesum/result.gamecount;
               var newRate=Math.round(orate*10)/10;
               if (newRate.toString().indexOf('.')==-1) newRate=newRate.toString()+'.0';
               ph.parent().parent().find('.rate'+ph.parent().attr('name')).html(newRate);
            }
            else if (text=='0' && typeof result.error != "undefined")
               alert(result.error)
            else
               alert('Vote has not been saved. Please, try again.');
            
            $('#loading').hide();
         });
      return false;
   };
   $('div.fon img').bind('click',div_fonImgClick);
   // donut
   $('img.donut').bind('click',div_fonImgClick);
   
   // comment tool
   // report
   var aReportAdmin_click=function()   
   {
      var id=$(this).parent().parent().parent().parent().parent().parent('div.commentblock').attr('id').substring(5);
      var th=$(this);
      $.get(tgSitesUri+'/site/commreportajax/'+id+'/',
         function(result,text)
         {
            th.parent().hide();
            alert('Report has been sent.');
         });
      return false;
   };
   $('a.aReportAdmin').bind('click',aReportAdmin_click);    
      
   // comment tool
   // report
   var aRepReportAdmin_click=function()
   {
      var id=$(this).parent().parent().parent().parent().parent('div.reply').attr('id').substring(5);
      var th=$(this);
      $.get(tgSitesUri+'/site/commreportajax/'+id+'/',
         function(result,text)
         {
            th.parent().hide();
            alert('Report has been sent.');
         });
      return false;
   };
   $('a.aRepReportAdmin').bind('click',aRepReportAdmin_click);      
   
   
// Comments
   var aDeleteComment_click=function()
   {
      if (!confirm('Selected comment will be deleted. Continue?')) return false;
      
      var id=$(this).parent().parent().parent().parent().parent().parent('div.commentblock').attr('id').substring(5);

      var th=$(this);
      $.get(tgSitesUri+'/site/commdelajax/'+id+'/',
         function(result,text)
         {
            if (text=='1')
            {
               alert('Comment has been deleted.');

               loadComments();
               
               $('#layer').hide();
               
               return false;
            }
            else if (text=='0') alert(result.error);
            else alert('Comment has not been deleted.');
         });
      return false;
   };
   $('a.aDeleteComment').bind('click',aDeleteComment_click);
   
   
   var btnSaveComment_click=function()
   {
      var id=$('#commid').val();
      var th=$(this);
      th.attr('disabled',true);
      th.next('input').attr('disabled',true);
      $.post(tgSitesUri+'/site/commupdateajax/',
         {commid:$('#commid').val(), commtext:$('#commedittext').val()},
         function(result,text)
         {
            if (text=='1')
            {
               alert('Comment has been updated.');
               
               $('#comm_'+id+' div.comment_text').html(result.commtext);
               commText='';
               
               return false;
            }
            else if (text=='0') alert(result.error);
            else alert('Comment has not been updated.');

            th.attr('disabled',false);
            th.next('input').attr('disabled',false);
         });
   };
   
   
   var btnCancelUpdate_click=function()
   {
      $('#comm_'+$('#commid').val()+' div.comment_text').html(commText);
      commText='';
   };
   
   var aEditComment_click=function()
   {
      if ($(this).parent().parent().parent().prev('div.comment_text').find('textarea').is('textarea'))
         return false;
      
	  var id=$(this).parent().parent().parent().parent().parent().parent('div.commentblock').attr('id').substring(5);
      commText=$(this).parent().parent().parent().prev('div.comment_text').html();
      var html=commText.replace(/<br[\/]?>/gi,"\n");
      
      $('#commedittext').parent('div.comment_body').html($('#commedittext').val());
      $(this).parent().parent().parent().prev('div.comment_text')
         .html('<textarea cols="75" style="width:100%" rows="10" id="commedittext" meta:validator="trim required strip_tags xss_clean">'+html+'</textarea><br/><input type="hidden" id="commid" value="'+id+'"/><input type="button" id="btnSaveComment" value="Submit"/> <input type="button" id="btnCancelUpdate" value="Cancel"/>')
         .find('#btnSaveComment').bind('click',btnSaveComment_click);
      $(this).parent().parent().parent().prev('div.comment_text')
         .find('#btnCancelUpdate').bind('click',btnCancelUpdate_click);
      
      return false;
   };
   $('a.aEditComment').bind('click',aEditComment_click);
   
// Comments End
   
// Comment Replies
   
   var btnReplyComment_click=function()
   {
      var id=$('#commid').val();
      var th=$(this);
      th.attr('disabled',true);
      th.next('input').attr('disabled',true);
      $.post(tgSitesUri+'/site/commreplyajax/',
         {commid:$('#commid').val(), commtext:$('#commedittext').val(), siteid:$('#siteid').val()},
         function(result,text)
         {
            if (text=='1')
            {
               loadComments();
               return false;
            }
            else if (text=='0') alert(result.error);
         });
   };   
   
   var btnCancelReply_click=function()
   {
      $('#comm_'+$('#commid').val()+' div.clearer').html('');
   };   
   
   var aPostReply_click=function()
   {
	  if ($(this).parent().parent().next('div.clearer').find('textarea').is('textarea'))
      return false;
      
	  var id=$(this).parent().parent().parent().parent().parent().parent().parent('div.commentblock').attr('id').substring(5);
      var html="";
      $(this).parent().parent().next('div.clearer')
         .html('<textarea cols="75" style="width:100%" rows="10" id="commedittext" meta:validator="trim required strip_tags xss_clean">'+html+'</textarea><br/><input type="hidden" id="commid" value="'+id+'"/><input type="button" id="btnReplyComment" value="Submit"/> <input type="button" id="btnCancelReply" value="Cancel"/>')
         .find('#btnReplyComment').bind('click',btnReplyComment_click);
      $(this).parent().parent().next('div.clearer')
         .find('#btnCancelReply').bind('click',btnCancelReply_click);
      
      return false;
   };
   $('a.aPostReply').bind('click',aPostReply_click);
   
   var aDeleteReply_click=function()
   {
      if (!confirm('Selected comment will be deleted. Continue?')) return false;
      
      var id=$(this).parent().parent().parent().parent().parent('div.reply').attr('id').substring(5);

      var th=$(this);
      $.get(tgSitesUri+'/site/commdelajax/'+id+'/',
         function(result,text)
         {
            if (text=='1')
            {
               alert('Comment has been deleted.');

               loadComments();
               
               $('#layer').hide();
               
               return false;
            }
            else if (text=='0') alert(result.error);
            else alert('Comment has not been deleted.');
         });
      return false;
   };
   $('a.aDeleteReply').bind('click',aDeleteReply_click);
   
   
   var btnSaveReply_click=function()
   {
      var id=$('#commid').val();
      var th=$(this);
      th.attr('disabled',true);
      th.next('input').attr('disabled',true);
      $.post(tgSitesUri+'/site/commupdateajax/',
         {commid:$('#commid').val(), commtext:$('#commedittext').val()},
         function(result,text)
         {
            if (text=='1')
            {
               alert('Comment has been updated.');
               
               $('#comm_'+id+' div.body').html(result.commtext);
               commText='';
               
               return false;
            }
            else if (text=='0') alert(result.error);
            else alert('Comment has not been updated.');

            th.attr('disabled',false);
            th.next('input').attr('disabled',false);
         });
   };
   
   
   var btnCancelReplyUpdate_click=function()
   {
      $('#comm_'+$('#commid').val()+' div.body').html(commText);
      commText='';
   };
   
   var aEditReply_click=function()
   {
      if ($(this).parent().next().next('div.body').find('textarea').is('textarea'))
         return false;
         
      var id=$(this).parent().parent().parent().parent().parent('div.reply').attr('id').substring(5);
      commText=$(this).parent().next().next('div.body').html();
      var html=commText.replace(/<br[\/]?>/gi,"\n");
      
      $('#commedittext').parent('div.body').html($('#commedittext').val());
      $(this).parent().next().next('div.body')
         .html('<textarea cols="75" style="width:100%" rows="10" id="commedittext" meta:validator="trim required strip_tags xss_clean">'+html+'</textarea><br/><input type="hidden" id="commid" value="'+id+'"/><input type="button" id="btnSaveReply" value="Submit"/> <input type="button" id="btnCancelReplyUpdate" value="Cancel"/>')
         .find('#btnSaveReply').bind('click',btnSaveReply_click);
      $(this).parent().next().next('div.body')
         .find('#btnCancelReplyUpdate').bind('click',btnCancelReplyUpdate_click);
      
      return false;
   };
   $('a.aEditReply').bind('click',aEditReply_click);
      
// Comment Reply End

// FR Reply

   var btnFRReplyComment_click=function()
   {
      var id=$('#commid').val();
      var th=$(this);
      th.attr('disabled',true);
      th.next('input').attr('disabled',true);
      $.post(tgSitesUri+'/site/frreplyajax/',
         {commid:$('#commid').val(), commtext:$('#commedittext').val(), siteid:$('#siteid').val()},
         function(result,text)
         {
            if (text=='1')
            {
               loadComments();
               return false;
            }
            else if (text=='0') alert(result.error);
         });
   };   
   
   var btnCancelFRReply_click=function()
   {
      $('#comm_'+$('#commid').val()+' div.clearer').html('');
   };   
   
   var aFRPostReply_click=function()
   {
	  if ($(this).parent().parent().next('div.clearer').find('textarea').is('textarea'))
      return false;
      
	  var id=$(this).parent().parent().parent().parent().parent().parent().parent('div.commentblock').attr('id').substring(5);
      var html="";
      $(this).parent().parent().next('div.clearer')
         .html('<textarea cols="75" style="width:100%" rows="10" id="commedittext" meta:validator="trim required strip_tags xss_clean">'+html+'</textarea><br/><input type="hidden" id="commid" value="'+id+'"/><input type="button" id="btnFRReplyComment" value="Submit"/> <input type="button" id="btnCancelFRReply" value="Cancel"/>')
         .find('#btnFRReplyComment').bind('click',btnFRReplyComment_click);
      $(this).parent().parent().next('div.clearer')
         .find('#btnCancelFRReply').bind('click',btnCancelFRReply_click);
      
      return false;
   };
   $('a.aFRPostReply').bind('click',aFRPostReply_click);
   
// FR Reply End
   
$(function()
{
   $('tr.foctr').each(function(){$(this).hide();});
   $('a.fnashow').focus(function(){this.blur();});
   $('a.fnashow').click(function()
   {
      if ($(this).parent().find('img.fnaimg').attr('src').indexOf('d.gif') > 0)
      {
         $(this).parent().find('img.fnaimg').attr('src', '/res/im/a/r.gif');
         $('tr.'+$(this).attr('name')).hide();
      }
      else
      {
         $(this).parent().find('img.fnaimg').attr('src', '/res/im/a/d.gif');
         $('tr.'+$(this).attr('name')).show();
      }
      return false;
   });
});
   
   // debug
   $("#msg").ajaxStart(function(){
      $(this).append("<li style=\"color:#00aa00\">Starting</li>");
   });
   $("#msg").ajaxSend(function(jq, request, settings){
      $(this).append("<li style=\"color:#0000ff\">Sending "+settings.url+"</li>");
   });
   $("#msg").ajaxComplete(function(request, settings){
      $(this).append("<li>Request Complete.</li>");
   });
   $("#msg").ajaxStop(function(){
      $(this).append("<li style=\"color:#c0c0c0\">Stopped</li>");
   });
   $("#msg").ajaxError(function(jq, request, settings){
      $(this).append("<li style=\"color:#ff0000\">Error requesting page " + settings.url + "</li>");
   });
});