(function($){
$.fn.extend({
  placeholder: function(text) {
    return this.each(function(){
      var obj = $(this);
      if (obj.val().length > 0 && obj.val() != text) {
        obj.attr('typed', '1');
      } else {
        obj.val(text).css('color', '#777');
      }
      obj.focus(function(){
        this.style.color = '#000';
        this.value =  this.getAttribute('typed') ? this.value : ''; 
      }).blur(function(){
        if ($.trim(this.value) == '') {
          this.value = text;
          this.setAttribute('typed', '');
          this.style.color = '#777';
        } else {
          this.setAttribute('typed', '1');
        }
      });
    });
  }
});
})(jQuery);


var submitted = false;

function submitItemForm(form) {
  // return if form is being submittеd
  if (submitted) {
    return false;
  }
  submitted = true;
  $.post('market.php?act=save', form.serialize(), function(data, textStatus) {
    if (data['error']) {
      $('#errorMessage').html('<div class="alertmsg">' + data['error'] + '</div>').slideDown('fast');
      submitted = false;
    } else {
      var photosForm = $('#photosForm').get(0);
      if (photosForm.file1.value) {
        photosForm.hash.value = data.hash;
        photosForm.rhash.value = data.rhash;
        photosForm.aid.value = data.album_id;
        photosForm.mid.value = data.mid;
        photosForm.gid.value = data.item_id;
        photosForm.submit();
      } else {
        location.replace('market.php?act=view&id='+data.item_id+'&show=my&m=1');
      }
    }
  }, 'json');
  return true;
}

function getSection(section) {
   if (section == undefined) {
     section = $('#section').val();
   }
   var current = $('#section' + section);
   if (current.length && current.hasClass('active') && delete_id == undefined) {
     return false;
   };
   $('#sections a').each(function(){
     if (this.className.indexOf('active') != -1) {
      this.className = this.className.substr(0, this.className.indexOf('active'));
     }
   });
   current.addClass('active');
   $('#itemsList').html('<div id="progressBar"></div>');
   
   if ($('#searchForm').length) {
     var selCat = $('#category');
     $('#section').val(section);
     selCat.val(0);
     if (!$('#searchField').attr('typed')) {
       $('#searchField').attr('disabled', 'disabled');
     }
     var data = $('#searchForm').serializeArray();
     $('#searchField').attr('disabled', '');
    
     if (section > 0) {
       var sectionCats = categories[section];
       
       var length = 0;
       selCat.empty();
       selCat.append('<option value="0">Все категории</option>');
       selCat.append('<option disabled="disabled">--------------------------------------</option>');
         
       for (var i in sectionCats) {
         length++;
         selCat.append('<option value="' + i + '">' + sectionCats[i] + '</option>');
       }
       if (length > 0) {
         selCat.show();
       } else {
         selCat.hide();
       }
     } else {
       selCat.hide();
     }
     
   } else {
     var data = {show: ge('show').value, section: section};
   }
   $('#itemsList').load('market.php?act=get_items', data);
   
   return false;
}

function getPage(offset) {
  $('#pageProgressTop').show();
  $('#pageProgressBottom').show();
  
  if ($('#searchForm').length) {
    var data = {
      q: ($('#searchField').attr('typed') ? $('#searchField').val() : ''),
      section: $('#section').val(),
      cat: $('#category').val(),
      show: $('#show').val(),
      st: offset
    };
  } else {
    var data = {
      show: 'my', 
      section:  $('#section').val(),
      st: offset
    }
  }
  
  $('#itemsList').load('market.php?act=get_items', data, function(){
    $('#pageProgressTop').hide();
    $('#pageProgressBottom').hide();
    $("html,body").animate({ 
      scrollTop: 0//$('#itemsList').position().top 
    }, "normal");
  });
  return false;
}

function deleteItem(id, where) {
 var hash = ge('faveHash').value;
 $.ajax({url: 'market.php?act=delete', type: 'post', data: {id: id, hash: hash, mode: where}, success: function(data, textStatus){
   if (where == 0) {hide('item'+id);} else {setOpacity(ge('item'+id), 50);} ge('res'+id).innerHTML = data; show('res'+id);
  }
 });
 return false;
}

function restoreItem(id, where) {
 var hash = ge('faveHash').value;
 $.ajax({url: 'market.php?act=restore', type: 'post', data: {id: id, hash: hash, mode: where}, success: function(data, textStatus){
   if (where == 0) {show('item'+id); hide('res'+id); ge('faved'+id).innerHTML = data;} else {setOpacity(ge('item'+id), 100); ge('res'+id).innerHTML = data; show('res'+id);} 
  }
 });
 return false;
}

function setOpacity(obj, percent) {
 if (isIE()) {
  var y = obj.offsetHeight;
  obj.style.height = y+"px";
  obj.style.filter = "alpha(opacity="+percent+")";
 } else {
  obj.style.opacity = percent/100;
 }
}

var reportBox;
var reason = 0;
function reportItem(id) {
  if (!reportBox) reportBox = new FadeBox({title: 'Жалоба'});
  reportBox.removeButtons().addButton({
    label:'Сохранить',
    onClick: function(){
     $.ajax({url: 'market.php?act=report', type: 'post', data: {id: id, reason: reason}, success: function(data, textStatus){
       ge('faved'+id).innerHTML = data; setOpacity(ge('item'+id), 50); show('faved'+id);
      }
     });
     reportBox.hide();
    }
  }).addButton({
    label: 'Отмена',
    style: 'buttonNo',
    onClick: function(){
      reportBox.hide();
    }
  }).content("Пожалуйста, выберите причину для блокировки объявления:<br /><br /><div id='marketReport'><div><input type='radio' name='reason' id='r1' onclick='reason=1' checked><label for='r1'>Спам / Сторонние ссылки</label></div><div><input type='radio' name='reason' id='r2' onclick='reason=2'><label for='r2'>Порнография</label></div><div><input type='radio' name='reason' id='r3' onclick='reason=3'><label for='r3'>Ложная информация / Мошенничество</label></div><div><input type='radio' name='reason' id='r4' onclick='reason=4'><label for='r4'>Несоответствие разделу</label></div><div><input type='radio' name='reason' id='r5' onclick='reason=5'><label for='r5'>Многократное дублирование</label></div><div><input type='radio' name='reason' id='r6' onclick='reason=6'><label for='r6'>Экстремизм</label></div><div><input type='radio' name='reason' id='r7' onclick='reason=7'><label for='r7'>Бессмыслица</label></div><div><input type='radio' name='reason' id='r8' onclick='reason=8'><label for='r8'>Орфографическая ошибка</label></div></div>").show();
  return false;
}

var photoBox;

function showPhoto(url, photo_id) {
  pic = new Image(); 
  pic.src = url; 
  if (!pic.width) {
   var coords = durovGetXY(ge('photo'+photo_id));
   ge('imageProgress').style.height = ge('photo'+photo_id).offsetHeight+"px";
   ge('imageProgress').style.left = coords[0]+"px";
   ge('imageProgress').style.top = coords[1]+"px";
   show('imageProgress');
   setTimeout("showPhoto('"+url+"')", 1500);
   return false;
  }
  if (!photoBox) photoBox = new FadeBox({type: 'POPUP', width: 'auto'});
  photoBox.content('<img src="' + url + '" />').show();
  hide('imageProgress');
  return false;
}

function durovGetXY(obj) {
 if (!obj || obj == undefined) return;
 var left = 0, top = 0;
 if (obj.offsetParent) {
  do {
   left += obj.offsetLeft;
   top += obj.offsetTop;
  } while (obj = obj.offsetParent);
 }
 return [left,top];
}


function addToFavesSearch(id) {
 ge('to_faves' + id).innerHTML = "<a onclick=\"return deleteFromFavesSearch("+id+");\" href='#' >Удалить из избранного</a>";
 $('#faved' + id).load('market.php?act=add_to_faves&mode=1', {id: id, hash: ge('faveHash').value});
 plusFave();
 return false;
}

function plusFave() {
 var fave_num = parseInt(ge('faveNum').value);
 if (fave_num == 0) {ge('market_tab').style.display = '';}
 ge('faveNum').value = fave_num + 1;    
}

function minusFave() {
 var fave_num = parseInt(ge('faveNum').value);
 if (fave_num == 1) {ge('market_tab').style.display = 'none';}
 ge('faveNum').value = fave_num - 1;    
}

function deleteFromFavesSearch(id) {
 ge('to_faves' + id).innerHTML = "<a onclick=\"return addToFavesSearch("+id+");\" href='#' >Добавить в избранное</a>";
 $('#faved' + id).load('market.php?act=delete_from_faves&mode=1', {id: id, hash: ge('faveHash').value});
 minusFave();
 return false;
}

function addToFaves(id) {
 var hash = ge('faveHash').value;
 $.ajax({url: 'market.php?act=add_to_faves', type: 'post', data: {id: id, hash: hash}, 
  success: function(data, textStatus){
   if (parseInt(data) == 1) {
    show('added_msg');
    hide('deled_msg');
    hide('add_to_faves');
    ge('delete_from_faves').style.display = '';
    plusFave();
   }
  }
 });
 return false;
}

function deleteFromFaves(id) {
 var hash = ge('faveHash').value;
 $.ajax({url: 'market.php?act=delete_from_faves', type: 'post', data: {id: id, hash: hash}, success: function(data, textStatus){
   if (parseInt(data) == 1) {
    hide('added_msg');
    show('deled_msg');
    hide('delete_from_faves');
    ge('add_to_faves').style.display = '';
    minusFave();
   }
  }
 });
 return false;
}

