﻿var currentPostPage = 1;
var zizzPopUpUnblock = ";";
var pwhere;
var removePostId;
var postInProgress = false;

$(document).ready(
  function()
  {
    if ($('#btnUploadPostPic').length > 0)
    ajaxup = new AjaxUpload('btnUploadPostPic',
                {
                  action: '/ajax/upload/Picture.ashx',
                  onSubmit: function(file , ext)
                            {
                              if ( !(ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
                              {
	                              displayError('Elfogadott formátumok: gif, jpg, png');
	                              return false;
                              }
                              else
                              {
                                $('#postpicUpload img').show();
                                this.disable();
                              }
                            },
                  data: {
                    type : 'post'
                  }, 
                  onComplete: function(file, response)
                              {
                                $('#postpicUpload img').hide();
                                this.enable();
                                try
                                {
                                  var resp = response.split('|');
                                  if (resp[1] == "success")
                                  {
                                    $('#hPostPicURL').val(resp[2].replace('/static/images/upload/', '/static/images/post/').replace('_crop', '_post'));
                                    $('#postPic img').attr('src', $('#hPostPicURL').val());
                                    $('#postpicUpload').hide();
                                    $('#postPic').show();
                                  }
                                  else
                                  {
                                    displayError('A feltöltés során hiba történt. Kérjük, próbáld meg később! (' + resp[2] + ')');
                                  }
                                }
                                catch(e)
                                {
                                  displayError('A feltöltés során hiba történt. Kérjük, próbáld meg később!');
                                }
                              },
                  onError: function(exception)
                           {
                             $('#postpicUpload img').hide(); 
                             this.enable();
                             displayError('A feltöltés során hiba történt. Kérjük, ellenőrizd, hogy a kép mérete nem haladja-e meg az 5 MB-ot!');
                           }
                }
          );
  }
);

function removePostPic()
{
  $('#hPostPicURL').val('');
  $('#postpicUpload').show();
  $('#postPic').hide();
}

function postFormValid()
{
  var valid = true;

  if ($('#txtPostText').val().replace(/[\n\s]/g, '') == '')
  {
    $('#postError').html("Nem írtál szöveget");
    valid = false;
  }
  else if ($('#txtPostText').val().replace(/[\n]/g, '').length > 140)
  {
    $('#postError').html("140 karakter lehet a szöveg");
    valid = false;
  }
  else if (/<[^>]*>/i.test($('#txtPostText').val()))
  {
    $('#postError').html("HTML kódok nem használhatók");
    valid = false;
  }
  
  return valid;
}

function addPost()
{
  if (!postInProgress && postFormValid())
  {
    postInProgress = true;
    $('.irjteis .gomb').html($('.irjteis .gomb').html() + ' <img src="/static/images/ajax-loader.gif" alt="" style="border:none; padding:5px 0px 0px 5px"/>');
    $.ajax(
      {
        url: "/ajax/DoAddPost.ashx",
        type: "POST",
        data: {
          text: $('#txtPostText').val().replace(/[\n]/g, ''),
          source: "web",
          replyto: '',
          pictureURL: $('#hPostPicURL').val(),
          videoURL: '',
          videoDuration: '',
          channelNames: $('#hChannelNames').val(),
          currentUrl: location.href
        },
        cache: false,
        dataType: 'json',
        timeout: 10000,
        success: function(jsonObj){
          $('.irjteis .gomb img').remove();
          defaultCallback(jsonObj);
          postInProgress = false;
        }
      }
    );
  }
}

function doLogin()
{
    $.ajax(
      {
        url: "/ajax/DoLogin.ashx",
        type: "POST",
        data: {
              nickname:  $('#txtNickName').val(),
              password: $('#txtPassword').val(),
              remember: $('#chkRemember').is(":checked")
        },
        cache: false,
        dataType: 'json',
        timeout: 10000,
        success: function(jsonObj){
            if (jsonObj.Redirect != "")
            {
              redirect(jsonObj.Redirect);
            }
            else
            {
              $('#errLogin').html('Hibás felhasználónév, vagy jelszó!');
            }
          }
      }
    );
}
   
function defaultCallback(jsonObj, statusText)
{
  $.unblockUI();
  displayResponse(jsonObj);
}

function displayError(message)
{
  alert(message);
}

function displayResponse(jsonObj)
{
  if (jsonObj.Redirect != "")
  {
    redirect(jsonObj.Redirect);
  }
  else
  {
    if (jsonObj.Message != "")
    {
      if (jsonObj.OnHide != undefined)
      {
        zizzPopUpUnblock = jsonObj.OnHide;
      }
     
      $('#modalText').html(jsonObj.Message.replace('csatornát', 'témát').replace('felhasználót', 'naplót'));
      tb_show('Zizz', '#TB_inline?height=150&width=300&inlineId=modalContainer&modal=true', false);
    }
  }
}

function hideZizzPopUp()
{
  $.unblockUI();
}

function redirect(url)
{
  location.href = url;
}

function getMorePosts(feed)
{
    $.ajax(
      {
        url: "/_5/ajax/GetMorePosts.ashx",
        type: "POST",
        data: {
                feed: feed,
                page: currentPostPage + 1
              },
        cache: false,
        global: false,
        dataType: 'json',
        timeout: 100000,
        beforeSend: function (XMLHttpRequest) {
          $('#morePostButton').html($('#morePostButton').html() + ' <img src="/static/images/ajax-loader.gif" alt="" style="border:none; padding:5px 0px 0px 5px"/>');
        },
        success: function(jsonObj){
          getMorePostsCallback(jsonObj);
        }
        ,error: function(XMLHttpRequest, textStatus, errorThrown){
        //debugger;
        //alert(errorThrown);
        }  
      }
    );
}


function getMorePostsCallback(jsonObj)
{
  if (jsonObj.Status == 'OK')
  {
    $('#morePostButton img').remove();
    currentPostPage = parseInt(jsonObj.Redirect);
    if (jsonObj.Message == jsonObj.Redirect) //maxpage == currentPage
    {
      $('#morePostButton').hide();
    }

    $(jsonObj.Data).appendTo($('#morePosts'));
    //postHandlers();
    //$.unblockUI();
  }
  else
  {
    defaultCallback(jsonObj);
  }
}

function doSearch(type, orderby, publiconly, startdate, enddate)
{ 
  var keyword = $('#txtKeyword').val();
  var makesearch = false;
  
  if (keyword == 'Mire keresel?' || keyword.match(/[\w\d]/) == null)
  {
      $('#txtKeyword').val('Mire keresel?');
  }
  else
  {
    makesearch = true;
  }
  
  if (makesearch)
  {
    $.ajax(
      {
        url: "/ajax/DoSearch.ashx",
        type: "POST",
        data: {
                type: type,
                keyword: keyword,
                orderby: orderby || "",
                publiconly: publiconly || "false",
                startdate: startdate || "",
                enddate: enddate || ""
              },
        cache: false,
        dataType: 'json',
        timeout: 10000,
        global: false,
        success: function(jsonObj){
          defaultCallback(jsonObj);
          }
       }
     );
  }
}

function showGame()
{
	 pwhere = 'domMessage';

	 AC_FL_RunContent(
					'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0',
					'width', '500',
					'height', '500',
					'src', '/_5/img/csocso8',
					'movie', '/_5/img/csocso8',
					'quality', 'high',
					'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
					'align', 'middle',
					'play', 'true',
					'loop', 'true',
					'scale', 'showall',
					'wmode', 'window',
					'devicefont', 'false',
					'id', 'csocso8',
					'bgcolor', '#ffffff',
					'name', 'csocso8',
					'menu', 'true',
					'allowFullScreen', 'false',
					'allowScriptAccess','false',
					'salign', ''
				);	

	$.blockUI({ message: $('#domMessage'), css: { width: '500px', top: '10%' } });
	$('.blockOverlay').click($.unblockUI);
	
	return false;
}

function removePost(postId)
{
  removePostId = postId;
  tb_show('Zizz', '#TB_inline?height=150&width=300&inlineId=delApprove&modal=true', false);
}

function doRemovePost()
{
  $.ajax(
    {
      url: "/ajax/DoRemovePost.ashx",
      type: "POST",
      data: { postId: removePostId },
      cache: false,
      dataType: 'json',
      timeout: 10000,
      success: function(jsonObj){
        location.reload();
        }
     }
   );
}