W_ABSPATH = '/1day1way/';
//W_ABSPATH = '/';
W_AJAX = W_ABSPATH + 'system/ajax/';
W_IMAGES = W_ABSPATH + 'content/images/';
W_BLOCKS = W_ABSPATH + 'content/blocks/';
W_CSS = W_ABSPATH + 'content/css/';

$(function () {
  //Задаём настройки для главного меню
  $("#menu .menuCell").mouseover(function() {
    $(this).attr("class", "onMenuCell");
  });
  $("#menu .menuCell").mouseout(function() {
    $(this).attr("class", "menuCell");
  });
  
  //Настройки для комментариев
  $('#comments>.comment:last').addClass('last');
  
//  $('#worksToScroll').scrollIt({
//		 scrollDuration : 230,
//		 scrollItwrapper : 'myMenuScroll'
// 	});
   $("#worksToScroll").wslide({
		 width: 180,
		 height: 130
   });

});

// Уничтожаем таймер
function killTimer(){
  if(timeoutId != null){
    clearTimeout(timeoutId);
    timeoutId = null;
  }
};


function tip(){}

//Функция вызывается, чтобы очистить input
tip.clearInput = function(item, text){
  if ($(item).val() == text) $(item).val("");
}
//Функция вызывается, когда мы убираем фокус с инпута
tip.blurInput = function(item, text){
  if ($(item).val() == "") $(item).val(text);
}
//Функция вызывается, когда мы убираем фокус с password input
tip.myBlurInputPassword = function(item, helpItem){
  if ($(item).val() == ""){
    $(item).hide();
    $(helpItem).show();
  }
}


//Функция обеспечивает отображение подсказок из альтов, расположенных в input
tip.initAllTips = function(){
  $("input[@alt]").each(function(i){
    tip.initOneTip(this);
  });
}
//Функция обеспечивает отображение подсказок из альтов, расположенных в input
tip.initBlockTips = function(itemBlock){
  $(itemBlock).find("input[@alt]").each(function(i){
    tip.initOneTip(this);
  });
}

tip.initOneTip = function(item) {
  var text = ($(item).attr("alt"));
  if ($(item).attr("type") != 'password') {
    tip.blurInput(item,text);
    
    $(item).focus(function() {tip.clearInput(item, text);});
    $(item).blur(function() {tip.blurInput(item, text);});
  }
  else{
    var passItem = item;
    var helpItem = $('<input class="inputT ' + $(item).attr('class') + '" type="text" value="' + text + '" />').attr('size', $(item).attr('size')).insertAfter(item);
    if ($(passItem).css('display') == 'none') {
      $(helpItem).hide();
    }
    else
      tip.myBlurInputPassword(item, helpItem);
    $(helpItem).focus(function() {helpItem.hide();$(passItem).show().focus();});
    $(item).blur(function() {tip.myBlurInputPassword(item, helpItem);});
  }
};

function validate(){}

//Проверка длины
validate.length = function(strToValidate, minLength, maxLength){
	if(strToValidate.length < minLength)
	  return false;
	if( (maxLength > 0) && (strToValidate.length > maxLength) )
	  return false;
	return true;
}

//Проверка соответствия регулярному выражению
validate.regural = function(strToValidate, regular){
  return regular.test();
}


//Выводит иконку об ошибке или о том, что все ок
validate.setErrorOrCorrect = function(el, type, alt){	  
  alt = alt || ""; 
  var imageName = "";
 if(type)
   imageName = 'correct.gif';
 else
   imageName = 'error.gif';
  var curImg = $(el).next("img");
	if($(curImg).length){
	  $(curImg).attr("src", W_IMAGES + 'icons/' + imageName);
	  $(curImg).attr("alt", alt);
	  $(curImg).attr("title", alt);
	}
	else
	  $(el).after('<img src="' + W_IMAGES + 'icons/' + imageName + '" class="errOrCor" title="' + alt + '" alt="' + alt + '" />');
}

//Вывести иконку об ошибке
validate.setError = function(el, alt){
  validate.setErrorOrCorrect(el, 0, alt);
}
//Вывести иконку об успехе
validate.setCorrect = function(el, alt){	  
	validate.setErrorOrCorrect(el, 1, alt);
}

function selectCategories (objSelect) {/*(idRoot, objOption) {*/
  var idRoot = $(objSelect).val();
  //var selectId = $(objSelect).attr('id');
  //var selectNum = selectId.substring(17, selectId.length);
  $.post(W_AJAX + "getCategories.php",
     { idRoot: idRoot },
     function(responseText) {
       //$('#subCat' + selectNum).html('<option value="-1">--</option>'  + responseText);
       $(objSelect).parent().next().find('select').html('<option value="-1">--</option>'  + responseText);
     }
  ); 
}

function nextCategory(selectNum) {
  $('.addCatBtn').remove();
  var nextCatHtml = '<tr><td><select id="cat' + selectNum + '" name="cat' + selectNum + '">';
  nextCatHtml += $('#cat' + (selectNum-1)).html();
  nextCatHtml += '</select></td><td><select id="subCat' + selectNum + '" name="subCat' + selectNum + '"><option value="-1">--</option></select></td></tr>';
  
  $('#subCat' + (selectNum-1)).parent().parent().after(nextCatHtml);
  
  $('#subCat' + selectNum).parent().after('<td><input type="button" class="deleteCatBtn" value="Удалить" onclick="deleteCategory(this)" /></td><td><input type="button" class="addCatBtn" value="+" onclick="nextCategory(' + (1 + parseInt(selectNum)) + ')" /></td>');
  $("#lastCat").val(selectNum);
}

function deleteCategory (objDelete) {
  $(objDelete).parent().parent().remove();
}
function post() {}
post.vote = function(element, essenceType, essenceId, mark){
	var url = W_AJAX + 'poll.php';
  $.post(url,
    {
      type: "application/x-www-form-urlencoded",
      essenceType: essenceType,
      essenceId:  essenceId,
      mark:  mark
    },
    function(responseText) {
    	alert(responseText);
    	var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
        $(element).parent().find('p').removeClass('empty').html(arrInfo['average_mark']);
        var secondImg = $(element).parent().find("img[src!='" + $(element).attr('src') + "']");
        if($(secondImg).attr('src') == W_IMAGES + 'icons/up.gif')
         $(secondImg).attr('src',  W_IMAGES + 'icons/upGrey.gif');
        else
         $(secondImg).attr('src',  W_IMAGES + 'icons/downGrey.gif');
      }
      else
        alert(arrInfo['err_text']); 
    });
}

post.submitComment = function(element){
  var essenceType = $('#inpEssenceType').val();
  var essenceId = $('#inpEssenceId').val();
  var rootComment = $('#inpRootComment').val();
  var commentText = $( $('#' + $('#textCommentText').attr('id') + 'IFrame').document() ).find('body').html();
  var isLinear = $("#comments[@type='linear']").length; //Линейность ответов
  var curModule = ($("#comments[@module]").length > 0) ? $("#comments").attr("module") : 'default'; //Текущий модуль
    
  var url = W_AJAX + 'add_comment.php'
  $.post(url,
    {
      type: "application/x-www-form-urlencoded",
      essenceType: essenceType,
      essenceId:  essenceId,
      rootComment:  rootComment,
      commentText:  commentText,
      linear: isLinear,
      module: curModule
    },
    function(responseText) {
      var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
        if (rootComment == '') {
          $('#comments').append(post.createCommentHTML(arrInfo['comment']));
          $('#comments .comment.last').removeClass('last');
          $('#comments>.comment:last').addClass('last');
          $('#no-comments').remove();
        }
        else {
          $('#com_' + arrInfo['comment']['root_comment']).append(post.createCommentHTML(arrInfo['comment']));
        }
        $('#commentForm').find('div').eq(0).html('');
        $('#subAddComment').remove();
        $('#commentsHead').text('Комментарии(' + arrInfo['comments_amount'] + ')');
        $('.commentsAmount').text('Комментарии(' + arrInfo['comments_amount'] + ')');
      }
      else {
        alert(arrInfo['err_text']);
      }
      
    });
}

post.createCommentHTML = function(arrComment) {
  var retText = '';
  retText += '<div class="comment" id="com_' + arrComment['ID_comment'] + '">';
    retText += '<div class="comInfo"><div class="overflow-hidden">';
        retText += '<div class="avatar45"><a href="' + W_ABSPATH + 'user/' + arrComment['login'] + '" title=""><img src="' + W_IMAGES + 'user/' + arrComment['ID_user'] + '/avatar/s_' + arrComment['ID_user'] + '.' + arrComment['pic_path'] + '" alt="" /></a></div>';
      retText += '<div class="author"><a href="' + W_ABSPATH + 'user/' + arrComment['login'] + '" title="">' + arrComment['first_name'] + ' ' + arrComment['first_name'] + ' (' + arrComment['login'] + ')'  +  '</a></div>';
      retText += '<p class="date">' + arrComment['creation'] + '</p>';
    retText += '</div>';
    retText += '</div>';
      //retText += '<p class="vote">0</p>';
      retText += '<div class="text">' + arrComment['text'] + '</div>';
      if (!arrComment['linear'])
        retText += '<p class="answer"><a href="#" onclick="post.moveFormToComment(this);return false;">Ответить</a></p>';
    
    //retText += '<div class="clear"></div>';
  retText += '</div>';
  return retText;
}
post.moveFormToComment = function(element) {
  $(element).parent().after($('#commentForm'));
  $('#commentForm').find('div').eq(0).html('<textarea id="textCommentText" class="wysiwygComment" cols="75" rows="3" name="commentText" />');
  $('#subAddComment').remove();
  $('#commentForm').find('div').eq(0).after('<input type="image" src="' + W_IMAGES + 'button/btnSend.gif" value="Опубликовать" id="subAddComment" name="addComment" onclick="post.submitComment();" />');
  $('#textCommentText').wysiwyg({ debug : true, wysiwygType : 'comment' });
  var tempVal = $(element).parent().parent().attr('id');
  tempVal = tempVal.substr(4);
  $('#inpRootComment').val(tempVal);
}

post.moveFormToRootComment = function() {
  $('#rootCommentHead').after($('#commentForm'));
  $('#commentForm').find('div').eq(0).html('<textarea id="textCommentText" class="wysiwygComment" cols="75" rows="3" name="commentText" />');
  $('#subAddComment').remove();
  $('#commentForm').find('div').eq(0).after('<input type="image" src="' + W_IMAGES + 'button/btnSend.gif" value="Опубликовать" id="subAddComment" name="addComment" onclick="post.submitComment();" />');
  $('#textCommentText').wysiwyg({ debug : true, wysiwygType : 'comment' });
  $('#inpRootComment').val('');
  
}


function work(){}

//Добавление категории к работе
work.addCategory = function() {
	var categoryNumber = $("tr.workCategory").size();
	categoryNumber = Number($("tr.workCategory:last").attr('categoryNumber')) + 1;
	var form = $("tr.workCategory[@categoryNumber=0]").html();
	form = form.replace(/_0/g, '_' + categoryNumber);
	form = form.replace(/\[0\]/g, '[' + categoryNumber + ']');
	form = form.replace(/\(0\)/g, '(' + categoryNumber + ')');
	form = form.replace(/Катеория 1/, 'Категория ' + (categoryNumber + 1));
	$("tr.workCategory[@categoryNumber=" + (categoryNumber - 1) + "]").after('<tr class="workCategory" categoryNumber="' + categoryNumber + '">' + form + '</tr>');
	$("#workCategoryRoot_" + categoryNumber).val("-1");
	$("#workCategorySub_" + categoryNumber).html('<option value="-1">--</option>');
	$("#workCategorySub_" + categoryNumber).parent().next().html(' <a href="#" onclick="work.remove(' + categoryNumber + '); return false;"><img src="' + W_IMAGES + 'icons/delete.gif" alt="" /></a>');
}

// Удаление напитка
work.remove = function(categoryNumber) {
	$("tr.workCategory[@categoryNumber=" + categoryNumber + "]").remove();
}

function displaySubCatalog(idItem) {
  var strHtml = Massiv[idItem];
  $("#subCatalogContent").html(strHtml);
}
function addToBasket(idWork, moveToBasket) {
$.post(W_AJAX + "basket/addToBasket.php",
     { idWork: idWork },
     function(responseText) {
      var arrResponse = JSON.parse(responseText);
       if (!arrResponse['result'])
        alert("Ошибка!!!!!!");
      else {
        $("#basketOut").html(arrResponse['basket']);
        if(moveToBasket == 1)
          document.location = W_ABSPATH + 'basket/';
        alert("Работа успешно добавлена в корзину!!!!!!");
      }
     }
     );
}

function changeBasketAmount(idWork) {
  workAmount = $("#basket" + idWork).val();
  workAmount = parseInt(workAmount);
  if (workAmount < 0)
    workAmount = 0;
  $.post(W_AJAX + "basket/changeBasketAmount.php",
     { idWork: idWork, workAmount: workAmount },
     function(newSum) {
        $("#basketSum").html("" + newSum + " руб.");
     }
     );
  
}

function deleteWorkFromBasket(idWork) {
  $.post(W_AJAX + "basket/deleteWorkFromBasket.php",
     { idWork: idWork },
     function(responseText) {
       if (!responseText)
        alert("Ошибка!!!!!!");
      else {
        $("#basket" + idWork).parent().parent().parent().empty();
        $("#basketSum").html("" + responseText + " руб.");
        alert("Работа успешно удалена из корзины!!!!!!");
      }
     }
     );
  
}

