function showbig(picname){
  window.open('/includes/foto.php5?pic='+picname,'_blank','scrollbars=yes,taskbar=no,resizeable=no,status=no,menubar=no,top=30,left=30,width=30,height=30');
}

function PreLoad(source){
  var NewImage = new Image();
  NewImage.src = source;
}

function prepareSubmit(frm){
  var len = frm.all("editbox").length; if (!len) len = 1;
  for (var i=0; i<len; i++)
  frm.all("codebox", i).innerText = frm.all("codebox", i).style.display ? borderOn(frm.all("codebox", i).innerText) : borderOn(frm.all("editbox", i).innerHTML);
}

function menuProcess(menuId){
  if(menuId.style.display == 'none'){
    menuId.style.display = 'block';
  }else{
    menuId.style.display = 'none';
  }
}

function btShowFunctionArguments(name){
  btChangeFunctionArgumentsBlock(name,'none','block','block');
}

function btHideFunctionArguments(name){
  btChangeFunctionArgumentsBlock(name,'block','none','none');
}

function btChangeFunctionArgumentsBlock(name,plus,minus,arguments){
  document.getElementById('backtrace_img_plus_'+name).style.display = plus;
  document.getElementById('backtrace_img_minus_'+name).style.display = minus;
  document.getElementById('backtrace_arguments_'+name).style.display = arguments;
}

function processTree(elementId,isTop){
  tbl = document.getElementById('dir_'+elementId);
  img = document.getElementById('img_'+elementId);

  if(tbl.style.display != 'none'){
    tbl.style.display = 'none';
    img.alt = 'Раскрыть';
    if(isTop)
    img.src = '/images/design/tree_plus.gif';
    else
    img.src = '/images/design/tree_sub_plus.gif';
  }else{
    tbl.style.display = 'block';
    img.alt = 'Закрыть';
    if(isTop)
    img.src = '/images/design/tree_minus.gif';
    else
    img.src = '/images/design/tree_sub_minus.gif';
  }
}

/**
* Преобразует многомерный обьект данных в строковое представление
*/
function Dump(d,l) {
  if (l == null) l = 1;
  var s = '';
  if (typeof(d) == "object") {
    s += typeof(d) + " {\n";
    for (var k in d) {
      for (var i=0; i<l; i++) s += "    ";
      s += k+": " + Dump(d[k],l+1);
    }
    for (var i=0; i<l-1; i++) s += "  ";
    s += "}\n"
  } else {
    s += "" + d + "\n";
  }
  return s;
}

function  print_r(arr){
  alert(Dump(arr));
}

/**
* Создаёт копию обьекта (для передачи не по ссылки)
*/
function clone(d) {
  var s = new Array();
  if(typeof(d) == "object"){
    for (var k in d)
    s[k] = clone(d[k]);
  }else
  s = d;
  return s;
}

/** v 1.1
* Выдаёт окончание
*
* @param int $count - Количество элементов
* @param str $word - название элемента в ед. числе
* @return str - название в указанном количестве
*/
function rus_case(count, word){
  var sp_count = (1 * count % 100 - 1 * count % 10) == 10;
  var count = 1 * count % 10;
  var mod = word.substr(word.length-1, 1);
  if(count == 1 && !sp_count)
  return word;
  switch (mod){
    case 'а' :
    if((count==2 || count==3 || count==4) && !sp_count)
    return word.substr(0, word.length-1) + 'ы';
    else
    return word.substr(0, word.length-1);
    case 'ь' :
    if((count==2 || count==3 || count==4) && !sp_count)
    return word.substr(0, word.length-1) + 'я';
    else
    return word.substr(0, word.length-1) + 'ей';
    case 'е' :
    if((count==2 || count==3 || count==4) && !sp_count)
    return word.substr(0, word.length-1) + 'я';
    else
    return word.substr(0, word.length-1) + 'й';
    default:
    if((count==2 || count==3 || count==4) && !sp_count)
    return word + 'а';
    else
    return word + 'ов';
  }
}



String.prototype.replaceAll = function(search, replace){
  return this.split(search).join(replace);
}

function showGirl(){
  if ($('#middle-left .middle-left-top div.img1').css('display')=='block'){
    vis = $('#middle-left .middle-left-top div.img1');
    novis = $('#middle-left .middle-left-top div.img2');
  } else if ($('#middle-left .middle-left-top div.img2').css('display')=='block') {
    vis = $('#middle-left .middle-left-top div.img2');
    novis = $('#middle-left .middle-left-top div.img3');
  } else if ($('#middle-left .middle-left-top div.img3').css('display')=='block') {
    vis = $('#middle-left .middle-left-top div.img3');
    novis = $('#middle-left .middle-left-top div.img1');
  }

  vis.fadeOut(2000);
  novis.fadeIn(2000);
}

function css3browsers(){
// / alert($.browser.version);
  if (($.browser.msie && $.browser.version >= 9) || ($.browser.opera && $.browser.version > 10.50) || $.browser.mozilla || $.browser.safari){
    return true;
  }
  
  return false;
}



$(document).ready(function(){
  $('a.clickme').click(function(){
    $('#searchHere').val($(this).text());
    $('#search').submit();    
    return false;
  })
  
  
  
  
  
  
  
  
  if (!css3browsers() && $('#main_menu .main_list li.selected_main').length){
    html =  $('#main_menu .main_list li.selected_main p').html();
    $('#main_menu .main_list li.selected_main p').remove();
    $('#main_menu .main_list li.selected_main').prepend('<div class="wrapper1"><div class="wrapper2"><p class="menu_name red">'+html+'</p></div></div>');
  }

  
  $('.temporary_banner').click(function(){return false;}).dblclick(function(){$(this).css('background','orange')});
  if ($('#auth .input-wrapper input').length){
    $('#auth .input-wrapper input[name="login"]').focus(function(){
      if ('Логин'==$(this).val()){
        $(this).val('')
      }
    }).blur(function(){
      if (''==$(this).val()){
        $(this).val('Логин');
      }
    })
  }

  if ($('div.middle-left-top').length)
  setInterval('showGirl()',4500);

  remove = 0;

    tmpobj = new Object();
  $('.modify').click(function(){
  remove = 0;
    if ($(this).hasClass('delete')){
      step = $(this).parent().prev().prev().prev().find('input').val();
    } else if ($(this).hasClass('remove')){
      step = $(this).next().attr('step');
    } else if($(this).hasClass('add')){
      step = $(this).prev().attr('step');
    } else {
      step=0;
    }
    
    if ($(this).hasClass('delete')){
      remove = 1;
    }
      $(this).css('display','none');
      tmpobj = $(this);
//   alert();
    $.getJSON($(this).attr('href')+'?step='+step, function(data){
      if (data['answer'] == '1'){
          //alert(data.count);
        modifyBasket(data['inBasket']);
        modifyBasket(data['inBasket']);//#order_count_recipe_56764578_product_65349125-D68A-41B1-9573-E59D3F170063
          
        if ($('#order_count_' + data['cid']).attr('id') != 'undefined'){
          $('#order_count_' + data['cid']).attr('value', data['count']);
          if (data['count'] == 0 || data['count'] == null){
            $('#'+data['cid']).remove();
          }
          $('#orders_order_price').text(data['inBasket']['price_formed']);
        }

        if (data['components'] != undefined){
          for(i in data['components']){
            if ($('#order_count_'+ i).attr('id') != undefined){
              $('#order_count_'+i).attr('value', data['components'][i]);
            }
          }
        }

        if (data['recipe_deleted']){
          location.href = "/orders/confirmOrder/";
        }

        $('#' + data['cid'] + '_added').slideDown();
        setTimeout(function(){

          $('#' + data['cid'] + '_added').slideUp();
        }, 1000);

        $('#' + data['cid'] + '_in_basket').find('span:first').text(data['count']);
        if ($('#' + data['cid'] + '_in_basket').hasClass('empty') && data['count'] > 0){
          $('#' + data['cid'] + '_in_basket').slideDown();
          $('#' + data['cid'] + '_in_basket').removeClass('empty');
        }
        if (!$('#' + data['cid'] + '_in_basket').hasClass('empty') && data['coount'] == 0){
          $('#' + data['cid'] + '_in_basket').slideUp();
          $('#' + data['cid'] + '_in_basket').addClass('empty');
        }

       if (remove){  
         window.location.reload();
       }
          tmpobj.css('display','block');
      }
    });
    return false;
  });

  $('.remake_order').click(function(){

    $(this).slideUp();
    object = this;
    $.getJSON($(this).attr('href'), function(data){
      if (data['answer'] == '1'){
        modifyBasket(data['inBasket']);
        $(object).slideDown();
        $('#order_' + data['orderCid'] + '_added').slideDown();
        setTimeout(function(){
          $('#order_' + data['orderCid']+ '_added').slideUp();
        }, 1000);
      }
    });

    return false;
  });

  $('.favorite').click(function(){
    $.getJSON($(this).attr('href'), function(data){
      if (data['answer'] == '1'){
        $('#urlFavorite').slideUp(function(){
          if (data['newAction'] == 'add'){
            $('#urlFavorite').text('Добавить в избранное');
          } else if (data['newAction'] == 'remove'){
            $('#urlFavorite').text('Убрать из избранного');
          }
          $('#urlFavorite').attr('href', data['url']);
          $('#urlFavorite').slideDown();
        });
      } else {
      }
    });
    return false;
  });
var hrefto = '';
  $('#confirmOrder, #insertAndPay, #confirmOrder, #confirmOrderUpdate, #makeOrder').click(function(){
      if (this.id == 'insertAndPay' || this.id == 'makeOrder' ){
          hrefto = '/orders/'+this.id+'/';
          $.postForm('/index.php5?module=users&'+this.id+'&class=updateUserInfo', '#userOrders' ,function(){
              location.href = hrefto;
          },  'POST');
          return false;
      }
  });

  $('#saveInfo').click(function(){
    if (validateForm('saveInfo')){
      $('#userProfile').find('.info_row').each(function(){
        $(this).css('visibility', 'hidden');
      });
      $('#userProfile .userProfile').addClass('preloader');
      data = $.getFormData('#userInfo');
      $.getJSON('/users/profile/ajax',data, function(data){
        if (data['error'] == undefined){
          $('#infoInformer').text(data['message']);
        } else {
          $('#infoInformer').text(data['error']);
        }
        setTimeout(function(){
          $('#userProfile .userProfile').removeClass('preloader');
          $('#infoInformer').fadeIn('slow');
          $('#userProfile .info_row').each(function(){
            $(this).css('visibility', 'visible');

            setTimeout(function(){
              $('#infoInformer').fadeOut('slow');
            }, 1500);
          });
        },1000);
      });
    }
    return false;
  });

  $('.add_tip').click(function(){
    data = $.getFormData('#addComment');
    $.getJSON('/menu/comments/add/',data, function(data){
        location.href = location.href;
    });
    return false;
  });


  $('.remove_tip').click(function(){

    data = '';
    $.getJSON($(this).attr('href'),data, function(data){
      if (data['error'] == undefined) {
        $('#comment_'+data['comment_id']).slideUp(function(){
          $('#comment_'+data['comment_id']).remove();
        });

      } else {
        $('#order_' + data['comment_id'] + '_error').text(data['error']);
        $('#order_' + data['comment_id'] + '_error').slideDown();
        setTimeout(function(){
          $('#order_' + data['comment_id'] + '_error').slideUp();
        }, 1000);
      }
    });
    return false;
  });




  $('.comment_pages a').click(function(){
    page = parseFloat($(this).text());
    $('.comments_row').slideUp('slow', function(){
      $('.comments_row li').each(function(){
        $(this).css('display', 'none');
      });
      $('.page_'+page).each(function(){
        $(this).css('display', 'block');
      });
      $('.comments_row').slideDown();
    });
    return false;
  });

  $('#savePassword').click(function(){
    if (validateForm('saveInfo')){
      $('#userPassword').find('.info_row').each(function(){
        $(this).css('visibility', 'hidden');
      });
      $('#userPassword .userProfile').addClass('preloader');
      data = $.getFormData('#password');
      $.getJSON('/users/profile/ajax',data, function(data){

        if (data['error'] == undefined){
          $('#passwordInformer').text(data['message'])
        } else {
          $('#passwordInformer').text(data['error'])
        }
        setTimeout(function(){
          $('#userPassword .userProfile').removeClass('preloader');
          $('#userPassword .info_row').each(function(){
            $(this).css('visibility', 'visible');
            $('#passwordInformer').fadeIn('slow');
            setTimeout(function(){
              $('#passwordInformer').fadeOut('slow');
            }, 1500);
          });
        },1000);
      });
    }
    return false;
  });




  $('#saveCard').click(function(){
    $('#userDiscount').find('.info_row').each(function(){
      $(this).css('visibility', 'hidden');
    });
    $('#userDiscount .userProfile').addClass('preloader');
    data = $.getFormData('#discount_card');
    $.getJSON('/users/profile/ajax/',data, function(data){

      if (data['error'] == undefined){
        $('#cardInformer').text(data['message']);
      } else {
        $('#cardInformer').text(data['error']);
      }
      setTimeout(function(){
        $('#userDiscount .userProfile').removeClass('preloader');
        $('#userDiscount .info_row').each(function(){
          $(this).css('visibility', 'visible');
          $('#cardInformer').fadeIn('slow');
          setTimeout(function(){
            $('#cardInformer').fadeOut('slow');
          }, 1500);
        });
      },1000);
    });
    return false;
  });


  $('#rememberPass').click(function(){
    data = $.getFormData('#rememberPassword');
    $.getJSON('/index.php5?module=users&class=rememberPassword&ajax=1', data, function(data){

      $('#rememberInformer').text(data['message']);
      setTimeout(function(){
        $('#rememberInformer').fadeIn('slow');
        setTimeout(function(){
          $('#rememberInformer').fadeOut('slow');
        }, 1500);
      });
    },1000);
  });


  $('.order_count').keydown(function(){
    if ((event.keyCode < 38 || event.keyCode > 57) && event.keyCode != 8 ){
      return false;
    }
  });

  $('.order_count').keyup(function(){

  }).blur(function(){
    if (parseInt($(this).val()) == 0){
      $(this).val($(this).attr('step'));
    }
    updateOrder(this);
  });


  $('#searchHere').keydown(function(e){
    lastKeyPressCode = e.keyCode;
    switch(e.keyCode) {
      case 27:
      $("#searchPreview").addClass('hidden');
      return false;
      break;
      case 38: // up
      return false;
      case 40: // down
      return false;
      break;
      case 9:  // tab
      case 13: // return
      default:
      updateSearch(this);
      break;
    }
  }).blur(function(){
      setTimeout(function() {$("#searchPreview").addClass('hidden');}, 1000);
  });


});


upTime = 500;
upSearchTime = 200;
objRequestDebounced = false;
objCountDebounceFn = false;
currentObject = '';

function updateSearch(obj){
  objRequestDebounced = true;
  if (!objCountDebounceFn) {
    objCountDebounceFn = $.debounce(function(){renewSearch(obj)}, upSearchTime);
  }

  objCountDebounceFn();
}


function findValue(li) {
  if( li == null ) return alert("No match!");

  // if coming from an AJAX call, let's use the CityId as the value
  if( !!li.extra ) var sValue = li.extra[0];

  // otherwise, let's just display the value in the text box
  else var sValue = li.selectValue;

  alert("The value you selected was: " + sValue);
}

function selectItem(li) {
  findValue(li);
}

function formatItem(row) {
  return row[0] + " (id: " + row[1] + ")";
}

function lookupAjax(){
  var oSuggest = $("#CityAjax")[0].autocompleter;

  oSuggest.findValue();

  return false;
}

function lookupLocal(){
  var oSuggest = $("#CityLocal")[0].autocompleter;

  oSuggest.findValue();

  return false;
}


function renewSearch(obj){
  url = '/index.php5?module=other&isAjax=1&class=search&searchStr='+$(obj).attr('value');
  $.getJSON(url, function(data){
    makeSearchMenu(data);
  });
}

function makeSearchMenu(data){
  $('#searchPreview').addClass('loading');

  $('#searchPreview ul li').each(function(){
    $(this).remove();
  });


  if (data != "empty"){

    for(i in data){
      //alert(data[i]['url'] + ' -> ' + data[i]['name']);
      elements = true;
      search_li = document.createElement('li');
      link = document.createElement('a');
      $(link).text(data[i]['name']);
      $(link).attr('rel', i);
      $(link).attr('href', data[i]['url']);
      $(search_li).bind('mouseover', function(){ $(this).addClass('mouseOver') });
      $(search_li).bind('mouseout', function(){ $(this).removeClass('mouseOver') });
      $(search_li).append(link);
      $('#searchPreview ul').append(search_li);
    }
  } else {

    search_li = document.createElement('li');
    $(search_li).text('Ничего не найдено');
    $('#searchPreview ul').append(search_li);
  }

  $('#searchPreview').removeClass('hidden');

}




function updateOrder(obj) {
  objRequestDebounced = true;
  if (!objCountDebounceFn) {
    objCountDebounceFn = $.debounce(function(){setOrderCount(obj)}, upTime);
  }

  objCountDebounceFn();
}

function setOrderCount(obj){

  url = ($(obj).attr('rel')+$(obj).attr('value'));

  $.getJSON(url, function(data){
    if (data['answer'] == '1'){
      modifyBasket(data['inBasket']);
      if ($('#orders_order_price').attr('id') != undefined){

        $('#orders_order_price').text(data['inBasket']['price_formed']);
      }
      $('#basketAdded').slideDown();
    }
  });
}



function validateForm(id){
  return true;
}

function modifyBasket (options){
  if (typeof(options['count']) != 'undefined' && typeof(options['price']) != 'undefined'){
    if ($('#myBasket').attr('id') != 'undefined'){
      if ($('#current_order_count').length && typeof options['count'] != 'undefined'){
        $('#current_order_count').text(options['count']);
      }
      if ($('#current_order_count_recipes').length && typeof options['recipes'] != 'undefined'){
        $('#current_order_count_recipes').text(options['recipes']);
      }
      if ($('#current_order_count_products').length && typeof options['products'] != 'undefined'){
        $('#current_order_count_products').text(options['products']);
      }
      if (options['count'] == 0){
        location.href = location.href;
      }
      $('#current_order_price').text(options['price']);
      if (options['count'] == 0 && !$('#myBasket').hasClass('empty')){
        $('#myBasket').slideUp();
        $('#myBasket').addClass('empty');
      }
      if (options['count'] != 0 && $('#myBasket').hasClass('empty')){
        $('#myBasket').slideDown();
        $('#myBasket').removeClass('empty');
      }
    }
  } else {
    $('#myBasket').slideUp();
    $('#myBasket').addClass('empty');
  }
}


(function($) {
  $.extend({

    postForm: function(url, form, callback, type){
      data = new Object();

      this.isArrayElement = function (name) {
        return name.substring(name.length 	 - 2);
      }

      $(form).find('input[name!=""],select[name!=""],textarea[name!=""]').each(function(id, element){
        jElement = jQuery(element);
        tagName = jElement.attr('tagName');

        elementName = jElement.attr('name');
        isArray = elementName.substring(elementName.length - 2) == '[]';
        elementValue = false;

        switch (tagName.toLowerCase()) {
          case 'input':

          elementType = jElement.attr('type');

          switch (elementType) {
            case 'checkbox':
            if (jElement.attr('checked') == true) {
              elementValue = jElement.val();
            }
            break;
            default:
            elementValue = jElement.val();
            break;
          }
          break;
          case 'select':
          if (isArray) {
            data[elementName] = new Array();
            optionsCount = 0;
            jElement.find('option').each(function(optionId, option){
              jOption = jQuery(option);
              if (jOption.attr('selected')) {
                data[jElement.attr('name')][optionsCount++] = jOption.val();
              }
            });
          } else {
            elementValue = jElement.val()
          }
          break;
          case 'textarea':

          elementValue = jElement.val();

          break;
        }

        if (isArray) {
          if (!data[elementName])  {
            data[elementName] = new Array();
          }

          newElementId = data[elementName].length;
          if (elementValue) {
            data[elementName][newElementId] = elementValue;
          }
        } else if(elementValue) {
          data[elementName] = elementValue;
        }
      });

      if (typeof type != 'undefined' && type == 'json') {
        postFn = jQuery.postJSON;
      } else {
        postFn = jQuery.post;
      }

      delete(elementValue);

      postFn(url, data, callback);
    },

    debounce : function(fn, timeout, invokeAsap, context) {

      if(arguments.length == 3 && typeof invokeAsap != 'boolean') {
        context = invokeAsap;
        invokeAsap = false;
      }

      var timer;

      return function() {

        var args = arguments;

        if(invokeAsap && !timer) {
          fn.apply(context, args);
        }

        clearTimeout(timer);

        timer = setTimeout(function() {
          if(!invokeAsap) {
            fn.apply(context, args);
          }
          timer = null;
        }, timeout);

      };

    },

    getFormData: function(form){
      data = new Object();
      this.isArrayElement = function (name) {
        return name.substring(name.length 	 - 2);
      }
      $(form).find('input[name!=""],select[name!=""],textarea[name!=""]').each(function(id, element){
        jElement = jQuery(element);
        tagName = jElement.attr('tagName');
        elementName = jElement.attr('name');
        isArray = elementName.substring(elementName.length - 2) == '[]';
        elementValue = false;

        switch (tagName.toLowerCase()) {
          case 'input':
          elementType = jElement.attr('type');

          switch (elementType) {
            case 'checkbox':
            if (jElement.attr('checked') == true) {
              elementValue = jElement.val();
            }
            break;
            default:
            elementValue = jElement.val();
            break;
          }
          break;
          case 'select':
          if (isArray) {
            data[elementName] = new Array();
            optionsCount = 0;
            jElement.find('option').each(function(optionId, option){
              jOption = jQuery(option);
              if (jOption.attr('selected')) {
                data[jElement.attr('name')][optionsCount++] = jOption.val();
              }
            });
          } else {
            elementValue = jElement.val()
          }
          break;
          case 'textarea':
          elementValue = jElement.val();
          break;
        }

        if (isArray) {
          if (!data[elementName])  {
            data[elementName] = new Array();
          }

          newElementId = data[elementName].length;
          if (elementValue) {
            data[elementName][newElementId] = elementValue;
          }
        } else if(elementValue) {
          data[elementName] = elementValue;
        }
      });

      return data;
    }
  });
})(jQuery);
