﻿var zizzPopUpUnblock = ";";
var vSendPM;
var vSendFeedback;
var ajaxup;
var ajaxup2;
var cropApi;
var firstInvalidElement = null;
var pwhere;
var themeId = "zizz";
var tooltipBgColor = "#78bbfe";
var tooltipColor = "#ffffff";
var currentPostPage = 1;

$.fn.focusEnd=function(){return this.each(function(){var A=this;if(A.style.display!="none"){if($.browser.msie){A.focus();var B=A.createTextRange();B.collapse(false);B.select()}else{A.setSelectionRange(A.value.length,A.value.length);A.focus()}}})};

$(document).ready(
  function()
  {
    //global blockUI settings
    $.blockUI.defaults.overlayCSS.opacity = '0.1';
    $.blockUI.defaults.css.width = '100%';
    $.blockUI.defaults.css.left = '0';
    $.blockUI.defaults.css.top = '20%';
    $.blockUI.defaults.css.border = 'none';
    $.blockUI.defaults.css.backgroundColor = 'transparent';
    $.blockUI.defaults.css.cursor = 'default';
    $.blockUI.defaults.message = '';
    
    //$.blockUI.defaults.growlCSS.top = '70px';

    //global ajax settings
    $.ajaxSetup(
      {
        cache: false
      }
    );
    $().ajaxStart(showAjaxLoader);//.ajaxStop($.unblockUI);
 	  jQuery().ajaxError(function(event, request, settings)
	  {
	    displayError("Hiba lépett fel, kérjük, próbáld meg később!");
	  });
	  
	  //validation settings
	  jQuery.validator.setDefaults(
	    {
	      errorClass: 'formFieldInvalid',
        errorElement: 'div',
        errorPlacement: function(error, element) {
          var $errorDiv = element.parent().parent().find('td:last div');
          if ($errorDiv.length > 0)
          {
            firstInvalidElement = firstInvalidElement || element;
            $errorDiv.qtip('api').destroy();
            addTip($errorDiv, error.html());
          }
        },
        highlight: function(element, errorClass) {
           if ($(element).attr('type') == 'checkbox')
           {
             $(element).parent().css('background-color', '#ed165d');
           }
           else
           {
             $(element).addClass(errorClass);
             $errorDiv = $(element).parent().parent().find('td:last div');
             if ($errorDiv.length > 0)
             {
               $errorDiv = $(element).parent().parent().find('td:last div');
               $errorDiv.addClass('formTableTooltipAlert');
             }
           }
        },
        unhighlight: function(element, errorClass) {
           if ($(element).attr('type') == 'checkbox')
           {
             $(element).parent().css('background-color', 'Transparent');
           }
           else
           {
             $(element).removeClass(errorClass);
             $errorDiv = $(element).parent().parent().find('td:last div');
             if ($errorDiv.length > 0)
             {
               $errorDiv.removeClass('formTableTooltipAlert');
               $errorDiv.qtip('api').destroy();
               addTip($errorDiv, $errorDiv.html());
             }
           }
        }
      }
    );

	  jQuery.validator.addMethod("nickname",
	    function(value, element)
	    {
	      return this.optional(element) || /^[a-zA-Z0-9_]+$/i.test(value);
      },
      "Hibás érték"
    );
	  jQuery.validator.addMethod("post",
	    function(value, element)
	    {
	      return this.optional(element) || !(/<[^>]*>/i.test(value));// || /[@#]/i.test(value));
      },
      "Hibás érték"
    );
	  jQuery.validator.addMethod("nohtml",
	    function(value, element)
	    {
	      return this.optional(element) || !(/<[^>]*>/i.test(value));
      },
      "Hibás érték"
    );
    jQuery.validator.addMethod("phoneprovider",
      function(value, element)
	    {
	      return this.optional(element) || /^[237][0]$/i.test(value);
      },
      "Hibás érték"
    );
	  jQuery.validator.addMethod("datehu",
	    function(value, element)
	    {
		    var check = false;
		    
		    try
		    {
		      var re = /^\d{4}\.\d{1,2}\.\d{1,2}$/;
		      if(re.test(value))
		      {
			      var parts = value.split('.');
			      var yyyy = parseInt(parts[0],10);
			      var mm = parseInt(parts[1],10);
			      var dd = parseInt(parts[2],10);
  			    
			      var xdate = new Date(yyyy, mm-1, dd);
			      check = ( (xdate.getFullYear() == yyyy) && (xdate.getMonth() == mm - 1) && (xdate.getDate() == dd) );
		      }
			  }
			  catch(e)
			  {}
			  
		    return this.optional(element) || check;
      },
      "Hibás érték"
    );
	  jQuery.validator.addMethod("atleast14",
	    function(value, element)
	    {
		    var check = false;
		    
		    try
		    {
			      var parts = value.split('.');
			      var vYear = parseInt(parts[0],10);
			      var vMonth = parseInt(parts[1],10);
			      var vDate = parseInt(parts[2],10);
  			    
            var now = new Date();
            var todayDate = now.getDate();
            var todayMonth = now.getMonth();
            var todayYear = now.getFullYear();

          var age = 0;

          if(vDate <= todayDate)
          {
            if(vMonth <= todayMonth)
              age = todayYear - vYear + 1;
            else if(vMonth > todayMonth)
              age = todayYear - vYear;
          }
          else if(vDate > todayDate)
          {
            if(vMonth < todayMonth)
              age = todayYear - vYear -1;
            else
              age = todayYear - vYear -1;
          }

          check = (age >= 14);
			  }
			  catch(e)
			  {}
			  
		    return this.optional(element) || check;
      },
      "Hibás érték"
    );
    	  jQuery.validator.addMethod("atleast18",
	    function(value, element)
	    {
		    var check = false;
		    
		    try
		    {
			      var parts = value.split('.');
			      var vYear = parseInt(parts[0],10);
			      var vMonth = parseInt(parts[1],10);
			      var vDate = parseInt(parts[2],10);
  			    
            var now = new Date();
            var todayDate = now.getDate();
            var todayMonth = now.getMonth();
            var todayYear = now.getFullYear();

          var age = 0;

          if(vDate <= todayDate)
          {
            if(vMonth <= todayMonth)
              age = todayYear - vYear + 1;
            else if(vMonth > todayMonth)
              age = todayYear - vYear;
          }
          else if(vDate > todayDate)
          {
            if(vMonth < todayMonth)
              age = todayYear - vYear -1;
            else
              age = todayYear - vYear -1;
          }

          check = (age >= 18);
			  }
			  catch(e)
			  {}
			  
		    return this.optional(element) || check;
      },
      "Hibás érték"
    );
    
    jQuery.validator.addMethod("lessthan28",
	    function(value, element)
	    {
		    var check = false;
		    
		    try
		    {
			      var parts = value.split('.');
			      var vYear = parseInt(parts[0],10);
			      var vMonth = parseInt(parts[1],10);
			      var vDate = parseInt(parts[2],10);
  			    
            var now = new Date();
            var todayDate = now.getDate();
            var todayMonth = now.getMonth();
            var todayYear = now.getFullYear();

          var age = 0;

          if(vDate <= todayDate)
          {
            if(vMonth <= todayMonth)
              age = todayYear - vYear + 1;
            else if(vMonth > todayMonth)
              age = todayYear - vYear;
          }
          else if(vDate > todayDate)
          {
            if(vMonth < todayMonth)
              age = todayYear - vYear -1;
            else
              age = todayYear - vYear -1;
          }

          check = (age < 28);
			  }
			  catch(e)
			  {}
			  
		    return this.optional(element) || check;
      },
      "Hibás érték"
    );
    
     jQuery.validator.addMethod("enddate", function(value, element) {
           //var startDate = $('#txtStartDate').val();
           var startDate = $('.sDate').val();
           var startHour = $('#txtStartTime .hourcombo').val();
           var startMin = $('#txtStartTime .mincombo').val();
           var endHour = $('#txtEndTime .hourcombo').val();
           var endMin = $('#txtEndTime .mincombo').val();
           
           
           var checkTime = false;
           var checkDate = false;
		  
           var sDate = new Date();
            var startParts = startDate.split('.');

            var startYear = parseInt(startParts[0], 10);
            var startMonth = parseInt(startParts[1], 10);
            var startDay = parseInt(startParts[2], 10);
              
            sDate.setFullYear(startYear, startMonth, startDay);
     
	        var eDate = new Date();
            var endParts = value.split('.');
            
            var endYear = parseInt(endParts[0], 10);
            var endMonth = parseInt(endParts[1], 10);
            var endDay = parseInt(endParts[2], 10);
            
            eDate.setFullYear(endYear, endMonth, endDay);
          
            if(value != "")
            {
                if(Date.parse(eDate.toDateString()) >= Date.parse(sDate.toDateString()))
                {
                    if(Date.parse(eDate.toDateString()) == Date.parse(sDate.toDateString()))
                    {
                        if(endHour >= startHour)
                        {
                            if(endMin >= startMin)
                            {
                                checkTime = true;
                                checkDate = true;
                            }
                        }
                    }
                    else
                    {
                        checkTime = true;
                        checkDate = true;
                    }
                }
            }
		
		    return this.optional(element) || (checkDate && checkTime);
      
    }, "A végdátum nem lehet kisebb, mint a kezdődátum."
    
    );


    vSendPM = $('#frmSendPM').validate(
      {
        rules: {
          txtPMSubject: {
            required: true,
            maxlength: 50
          },
          txtPMMessage: {
            required: true,
            maxlength: 140
          }
        },
        messages: {
          txtPMSubject: {
            required: 'A mező kitöltése kötelező!',
            maxlength: 'Ennél hosszabb tárgya nem lehet az üzenetnek!'
          },
          txtPMMessage: {
            required: 'A mező kitöltése kötelező!',
            maxlength: 'Legfeljebb 140 karaktert írhatsz egy üzenetbe.'
          }
        }
	    }
	  );

    vSendFeedback = $('#frmSendFeedback').validate(
      {
        rules: {
          ddlFbcategory: {
            required: true
          },
          txtFbName: {
            required: true,
            maxlength: 100
          },
          txtFbEmail: {
            required: true,
            email: true,
            maxlength: 100
          },
          txtFbText: {
            required: true,
            maxlength: 2000
          }
        },
        messages: {
          ddlFbcategory: {
            required: 'A mező kitöltése kötelező!'
          },
          txtFbName: {
            required: 'A mező kitöltése kötelező!',
            maxlength: 'A beírt név túl hosszú.'
          },
          txtFbEmail: {
            required: 'A mező kitöltése kötelező!',
            email: 'Az e-mail cím formátuma nem megfelelő.',
            maxlength: 'A beírt e-mail cím túl hosszú.'
          },
          txtFbText: {
            required: 'A mező kitöltése kötelező!',
            maxlength: 'Legfeljebb 2000 karaktert írhatsz egy üzenetbe.'
          }
        }
	    }
	  );

	  //event handlers
	  $('#txtKeyword, #txtSearchKeyword').focus(
	    function()
	    {
	      $(this).select();
	    }
	  ).keypress(
      function(e)
      {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
        {
            doSearch($(this).attr('class'));
            return false;
        }
        else
        {
            return true;
        }
      }
    );
    
    //hovers
    addHover('btnReg', 'btnRegOn');
    addHover('btnPlay', 'btnPlayOn');
    addHover('btnApplicant', 'btnApplicantOn');
    addHover('btnReferrer', 'btnReferrerOn');
    addHover('button', 'buttonOn');
    
    postHandlers();

    //Tooltips
    switch (themeId)
    {
      case 'borsodi':
        tooltipBgColor = "#7DC402";
        break;
      case 'pingvin':
        tooltipBgColor = "#0D2A4F";
        break;
      case 'mz':
        tooltipBgColor = "#f9e5bf";
        break;  
      case 'olive':
        tooltipBgColor = "#96AD50";
        break;
    }
    
    //form fields
    $('div.formTableTooltip').each(function(i)
      {
        addTip($(this), $(this).html(), 200);
      }
    );
    
    //avatars
    $('img.followAvatar, #rightColContacts div:eq(0) a img, a.commentLineItemAvatar img').each(function(i)
      {
        if ($(this).parent().attr('title') != '')
        {
          addTip($(this), $(this).parent().attr('title'), 200);
          $(this).parent().attr('title', '');
        }
      }
    );
    
    //public/private lock
    $('img.publicstate').each(function(i)
      {
        addTip($(this), $(this).attr('title'), 130);
        $(this).attr('title', '');
      }
    );    
    
    //15mp channel hack
    var $ch15mpf = $('div.postItemPriority2 div a');
    if ($ch15mpf.length > 0)
      $ch15mpf.parent().prepend($('<span>' + $ch15mpf.html() + '</span>'));
  }
);

function showAjaxLoader()
{
  //$.blockUI({message: '<img src="/static/images/ajax-loader.gif"/>'});
  $.blockUI();
}

function addHover(cssClass, cssClassOn)
{
    $('.' + cssClass).hover(
      function ()
      {
        $(this).addClass(cssClassOn);
      }, 
      function ()
      {
        $(this).removeClass(cssClassOn);
      }
    );
}

function displayInfo(message, redir)
{
  redir = redir || "";
  displayResponse(eval('({"Status":"OK","Message":"' + message + '","Data":"","Redirect":"","Buttons":["OK|hideZizzPopUp();' + ((redir != "") ? "redirect(\'" + redir + "\')" : "") +'"]})'));
}


function displayError(message, redir)
{
  redir = redir || "";
  displayResponse(eval('({"Status":"ERROR","Message":"' + message + '","Data":"","Redirect":"","Buttons":["OK|hideZizzPopUp();' + ((redir != "") ? "redirect(\'" + redir + "\')" : "") +'"]})'));
}

//ajax response handling
function displayResponse(jsonObj)
{
  if (jsonObj.Redirect != "")
  {
    redirect(jsonObj.Redirect);
  }
  else
  {
    if (jsonObj.Message != "")
    {
      var msg = jsonObj.Message;

      if (jsonObj.Buttons == undefined)
      {
        $.blockUI.defaults.growlCSS.left = $('#containerContent').offset().left;
        if (jsonObj.OnHide != undefined)
        {
          zizzPopUpUnblock = jsonObj.OnHide;
          $.blockUI.defaults.onUnblock = popupUnblock;
        }
        $.blockUI({
          message: $('<div class="serviceWindow"><div class="serviceWindowBottom"><table width="100%" border="0" cellspacing="0" cellpadding="0" height="100%"><tr><td valign="middle">' + msg + '</td></tr></table></div></div>'),
           fadeIn: 700, fadeOut: 1000, centerX: true, centerY: true,
          timeout: 3000, showOverlay: false
        });
      }
      else
      {
        var buttons = '';
        for(i = 0; i < jsonObj.Buttons.length; i++)
        {
          var parts = jsonObj.Buttons[i].split("|");
          buttons += '<div class="' + ((jsonObj.Status == 'OK') ? 'buttonGeneralBigWhite' : 'buttonGeneralBigRed') + '" style="margin: 10px 20px 0px 0px;"><a href="javascript:' + parts[1] + '">' + parts[0] + '</a></div>';
        }

        showZizzPopUp((jsonObj.Status == 'OK'), msg, buttons, 450, 100);
      }
    }
  }
}

function popupUnblock()
{
  eval(zizzPopUpUnblock);
  $.blockUI.defaults.onUnblock = '';
}

function defaultCallback(jsonObj, statusText)
{
  $.unblockUI();
  displayResponse(jsonObj);
}

//popup functions
function showZizzPopUp(normal, msg, buttons, width, height)
{
  var msgType = (normal) ? 'service' : 'alert';  
  var $div = $('<div class="' + msgType + 'Window"><div class="' + msgType + 'WindowBottom"><table width="100%" border="0" cellspacing="0" cellpadding="0" height="100%"><tr><td valign="middle">' + msg + '<br />' + buttons + '</td></tr></table></div></div>');
  
  $.blockUI({ message: $div});
}

function hideZizzPopUp()
{
  $.unblockUI();
}

function redirect(url)
{
  location.href = url;
}


//public/private field handlers
function switchFieldPublicState(img)
{
  var $img = $(img);
  var text = "";
  if ($img.attr('src').indexOf('_private') != -1)
  {
    $img.attr('src', $img.attr('src').replace('_private', '_public'));
    text = $img.qtip('api').elements.content.html().replace('Privát','Nyilvános');
  }
  else
  {
    $img.attr('src', $img.attr('src').replace('_public', '_private'));
    text = $img.qtip('api').elements.content.html().replace('Nyilvános', 'Privát');
  }
  
  $img.qtip('api').destroy();
  addTip($img, text, 130);
}

function getFieldPublicState(selector)
{
  return ($(selector).attr('src').indexOf('_private') == -1) ? '0' : '1';
}


//post
function removePost(postId)
{
  $('#removeQuestion h2').html('A törlés végleges. Biztosan kitörlöd?');
  $.blockUI({ message: $('#removeQuestion') });
 
  $('#rmpqYes').click(function()
    {
      doRemovePost(postId);
      return false;
    }
  ); 

  $('#rmpqNo').click(function()
    {
      $.unblockUI(); 
      return false;
    }
  );
}

function doRemovePost(postId)
{
  $.ajax(
    {
      url: "/ajax/DoRemovePost.ashx",
      type: "POST",
      data: { postId: postId },
      cache: false,
      dataType: 'json',
      timeout: 10000,
      success: function(jsonObj){
        defaultCallback(jsonObj);
        }
     }
   );
}

//private messages
function sendPM(to, subject)
{
  $('#txtPMTo').html(to);
  $('#txtPMSubject').val(subject);
  $('#txtPMMessage').val('');
  $.blockUI({ message: $('#privateMessagePopUp')});
}

function doSendPM()
{
  if (vSendPM.form())
  {
    $.ajax(
      {
        url: "/ajax/DoSendPM.ashx",
        type: "POST",
        data: {
                to: $('#txtPMTo').html(),
                subject: '',//$('#txtPMSubject').val(),
                message: $('#txtPMMessage').val()
              },
        cache: false,
        dataType: 'json',
        timeout: 10000,
        success: function(jsonObj){
          defaultCallback(jsonObj);
          }
      }
    );
  }
}

function removePM(PMId)
{
  $('#removeQuestion h2').html('A törlés végleges. Biztosan kitörlöd?');
  $.blockUI({ message: $('#removeQuestion') });
 
  $('#rmpqYes').click(function()
    {
      doRemovePM(PMId);
      return false;
    }
  ); 

  $('#rmpqNo').click(function()
    {
      $.unblockUI();
      return false;
    }
  );  
}

function doRemovePM(PMId)
{
  $.ajax(
    {
      url: "/ajax/DoRemovePM.ashx",
      type: "POST",
      data: { PMId: PMId },
      cache: false,
      dataType: 'json',
      timeout: 10000,
      success: function(jsonObj){
        defaultCallback(jsonObj);
        }
     }
   );
}

//search
function doSearch(type, orderby, publiconly, startdate, enddate)
{ 
  var keyword = $('#txtKeyword').val();
  var keyword2 = $('#txtSearchKeyword').val();
  var makesearch = false;
  
  if (keyword == 'Mire keresel?' || keyword.match(/[\w\d]/) == null)
  {
    if (type == 'allmain')
    {
      $('#txtKeyword').val('Mire keresel?');
    }
    else
    {
      keyword = keyword2;
      makesearch = true;
    }
  }
  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);
          }
       }
     );
  }
}

//feedback
function sendFeedback()
{
  $('#txtFbName, #txtFbEmail, #txtFbText').val('');
  $.blockUI({ message: $('#feedbackPopUp') });
}

function doSendFeedback()
{
  if (vSendFeedback.form())
  {
    $.ajax(
      {
        url: "/ajax/DoSendFeedback.ashx",
        type: "POST",
        data: {
                category: $('#ddlFbcategory').val(),
                name: $('#txtFbName').val(),
                email: $('#txtFbEmail').val(),
                text: $('#txtFbText').val()
              },
        cache: false,
        dataType: 'json',
        timeout: 10000,
        success: function(jsonObj){
          defaultCallback(jsonObj);
          }
      }
    );
  }
}

//themes

function setThemeHovers()
{
  $('img.tableBgSelect, img.tableBgSelectOn').unbind('hover');
  $('img.tableBgSelect').hover(
    function ()
    {
      $(this).addClass('tableBgSelectOn');
    }, 
    function ()
    {
      if (!$(this).hasClass('selected'))
      {
        $(this).removeClass('tableBgSelectOn');
      }
    }
  );
}

function setUserCSS($bgImg, $bgRpt)
{
  var picURL = $bgImg.attr('src').replace('_preview', '');
  if (picURL.indexOf('theme') == -1)
  {
    $.ajax(
      {
        url: "/ajax/CreateCSS.ashx",
        type: "POST",
        data: {
                themeId: $('#hThemeId').val(),
                background_image:  picURL,
                background_repeat: $bgRpt.is(":checked")
              },
        cache: false,
        dataType: 'json',
        timeout: 100000,
        success: function(jsonObj){
            hideZizzPopUp();
            if (jsonObj.Status == 'OK')
            {
              var rnd = new Date().getTime() - new Date(2009,4,1).getTime();
              $('#ctl00_linkThemeCss').attr('href', jsonObj.Message.replace('/static', '/static/' + rnd));
              fixFieldPublicSatateImages($('#hThemeId').val());
            }
          }
      }
    );
  }
}

function fixFieldPublicSatateImages(themeId)
{
  $("img[src*='field_public']").each(
    function(i)
      {
        $(this).attr('src', $(this).attr('src').replace(/\/theme\/.*/, '/theme/' + themeId + '/field_public_' + themeId + '.gif'));
      }
  );
  $("img[src*='field_private']").each(
    function(i)
      {
        $(this).attr('src', $(this).attr('src').replace(/\/theme\/.*/, '/theme/' + themeId + '/field_private_' + themeId + '.gif'));
      }
  );  
  $("img[src*='form_info_icon']").each(
    function(i)
      {
        $(this).attr('src', $(this).attr('src').replace(/\/theme\/.*/, '/theme/' + themeId + '/form_info_icon_' + themeId + '.gif'));
      }
  );  
}

function showFirstInvalidElement()
{
  if (firstInvalidElement != null)
  {
    $.scrollTo(firstInvalidElement, 300);
  }
}

function showPostPicPreview(obj)
{
  $('#layerPreview #imgPreview').attr('src', obj.attr('src').replace("_post.", "_preview.")).parent().attr('href', obj.attr('src').replace("_post.", "."));
  $('#layerPreview').css({ bottom: Math.min($(window).height()-(obj.offset().top+obj.height()-$(window).scrollTop()-20), $(window).height()-500) + 'px', left: Math.max(obj.offset().left+obj.width()-540, 20) + 'px'});
  $.blockUI({ message: $('#layerPreview'), css: {top:'0px', left:'0px', height: '100%'}, overlayCSS: {opacity: '0.3'} });
}

function closePostPicPreview()
{
  hideZizzPopUp();
  $('#layerPreview #imgPreview').attr('src', '/static/images/zizz_logo.png');
}

function showPostVideoPlayer(obj)
{
  pwhere = 'layerVideoWrapper';

  if (DetectFlashVer(9, 0, 0))
  {
		 AC_FL_RunContent(
					"src", "",
					"movie","/static/images/theme/" + themeId + "/video_player?bufferlength=10&autostart=true&file=" + obj.attr("src").replace(".jpg", ".flv"),
					"width", "670",
					"height", "401",
					"wmode", "transparent",
					"align", "middle",
					"id", "zizzVideoPlayer",
					"name", "zizzVideoPlayer",
					"quality", "high",
					"bgcolor", "#FFFFFF",
					"allowScriptAccess", "always",
					"allowfullscreen", "true",
					"fullscreen",	"false",
					"stretching",	"fill",
					"duration", "63",
					"type", "application/x-shockwave-flash",
					'codebase', 'http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab',
					"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
		
		$('#layerVideo').css({ top: ($(window).height()-460)/2 + 'px', left: $('#postArea').offset().left-10 + 'px'});
    $.blockUI({ message: $('#layerVideo'), css: {top:'0px', left:'0px', height: '100%'}, overlayCSS: {opacity: '0.3'} });
	}
	else
	{
    displayError("A videó megtekintéséhez frissítsd a Flash lejátszód!");
	}
}

function closePostVideoPlayer()
{
  $('#layerVideoWrapper').empty();
  hideZizzPopUp();
}

function showMemberFind(origo)
{
  $.cookies.set('memberFindOrigo', origo, {path : '/', hoursToLive: .01});
  redirect('/members/place');
}

function addTip(obj, content, tipWidth)
{
  obj.qtip(
    {
      content: { text: content, prerender: false },
      position: {
        //target: 'mouse',
        adjust:{ mouse: true, screen: true, scroll: false, x: 20, y: -24}
      },
      style: {
        border: {
           width: 3,
           radius: 5,
           color: tooltipBgColor
        },
        width: tipWidth,
        background: tooltipBgColor,
        color: tooltipColor,
        padding: '0px'
      }
    }
  );
}

function postHandlers()
{
    $('.postItem').hover(
      function ()
      {
        $(this).addClass('postItemOn').removeClass('postItem');
      }, 
      function ()
      {
        $(this).addClass('postItem').removeClass('postItemOn');
      }
    );
    
    $('.postItemLocation').hover(
      function ()
      {
        $(this).addClass('postItemLocationOn').removeClass('postItemLocation');
      }, 
      function ()
      {
        $(this).addClass('postItemLocation').removeClass('postItemLocationOn');
      }
    );
    
    addHover('postActionComment', 'postActionCommentOn');
    addHover('postActionFavorite', 'postActionFavoriteOn');
    addHover('postActionReply', 'postActionReplyOn');
    addHover('postActionTrash', 'postActionTrashOn');
    addHover('postActionAllow', 'postActionAllowOn');
    addHover('postActionBlock', 'postActionBlockOn');
    addHover('postActionEdit', 'postActionEditOn');
    
    //avatars
    $('img.postAvatar').each(function(i)
      {
        if ($(this).parent().attr('title') != '')
        {
          addTip($(this), $(this).parent().attr('title'), 200);
          $(this).parent().attr('title', '');
        }
      }
    );
    
    //post actions
    $('.postActionComment, .postActionFavorite, .postActionReply, .postActionTrash, .postActionAllow, .postActionBlock').each(function(i)
      {
        addTip($(this), $(this).attr('title'), 130);
        $(this).attr('title', '');
      }
    );
    
    //user/channel links
    $('.postItem p, .commentAreaText').each(function(i)
      {
        $(this).html($(this).html().replace(/([^>]*?)([@#])([a-zA-Z0-9_]{3,})/g, '$1<a href="/$3" class="postItemUser">$2$3</a>'));
      }
    );
    
    //post picture preview
    $('.uploadPic').each(function(i)
      {
        $(this).parent().click(function()
          {
            showPostPicPreview($(this).find('img'));
            return false;
          }
        );
      }
    );
    
    //post video player
    $('.uploadVideo').each(function(i)
      {
        $(this).parent().click(function()
          {
            showPostVideoPlayer($(this).find('img'));
            return false;
          }
        );
      }
    );
    
    //post rating
    $('.pRate').rating({ 
      callback: function(value, link)
        {
          var postId = $(link).parent().parent().parent().find('input.pRate').attr('name').replace("rt", "");
          $.ajax(
          {
            url: "/ajax/DoRatePost.ashx",
            type: "POST",
            data: {
                    postid: postId,
                    ratevalue: parseFloat(value.replace(',', '.'))*1000
                  },
            cache: false,
            dataType: 'json',
            timeout: 10000,
            success: function(jsonObj){
                hideZizzPopUp();
                if (jsonObj.Status == 'OK')
                {
                  //TODO: set new rating value
                }
              }
            }
          );
        } 
      }
    );
}

function getMorePostsHome()
{
    $.ajax(
      {
        url: "/ajax/GetMorePostsHome.ashx",
        type: "POST",
        data: {
                page: currentPostPage + 1,
                theme: themeId
              },
        cache: false,
        global: false,
        dataType: 'json',
        timeout: 100000,
        beforeSend: function (XMLHttpRequest) {
          $('#morePostButton').html('<img src="/static/images/ajax-loader.gif" alt="" style="border:none; padding-top:5px"/>');
        },
        success: function(jsonObj){
          getMorePostsCallback(jsonObj);
        }
      }
    );
}

function getMorePostsOwn()
{
    $.ajax(
      {
        url: "/ajax/GetMorePostsOwn.ashx",
        type: "POST",
        data: {
                page: currentPostPage + 1,
                theme: themeId
              },
        cache: false,
        global: false,
        dataType: 'json',
        timeout: 100000,
        beforeSend: function (XMLHttpRequest) {
          $('#morePostButton').html('<img src="/static/images/ajax-loader.gif" alt="" style="border:none; padding-top:5px"/>');
        },
        success: function(jsonObj){
          getMorePostsCallback(jsonObj);
        }
      }
    );
}

function getMoreMentions()
{
    $.ajax(
      {
        url: "/ajax/GetMoreMentions.ashx",
        type: "POST",
        data: {
                page: currentPostPage + 1,
                theme: themeId
              },
        cache: false,
        global: false,
        dataType: 'json',
        timeout: 100000,
        beforeSend: function (XMLHttpRequest) {
          $('#morePostButton').html('<img src="/static/images/ajax-loader.gif" alt="" style="border:none; padding-top:5px"/>');
        },
        success: function(jsonObj){
          getMorePostsCallback(jsonObj);
        }
      }
    );
}

function getMorePostsCallback(jsonObj)
{
  if (jsonObj.Status == 'OK')
  {
    $('#morePostButton').html($('#morePostButton').attr('title'));
    currentPostPage = parseInt(jsonObj.Redirect);
    if (jsonObj.Message == jsonObj.Redirect) //maxpage == currentPage
    {
      $('#morePostButton').hide();
    }

    $(jsonObj.Data).appendTo($('#morePosts'));
    postHandlers();
    $.unblockUI();
  }
  else
  {
    defaultCallback(jsonObj);
  }
}
