$(window).ready(function(){
  $('#container, img').pngFix();
  if ($(".content_right").length) $(".content_right").css('height', $("#content").height());
  $("input.inner-label").focus(function(){
    if(this.value == $(this).attr('default')) this.value = '';
  }).blur(function(){
    if(this.value.length == 0) this.value = $(this).attr('default');
  }).blur();
  
  $('#login_form').submit(function(){
    var error = '';
    if(innerLabelInputIsEmpty('password',this)) error = dictionary.loginPasswordRequired;
    if(innerLabelInputIsEmpty('username',this)) error = dictionary.loginUsernameRequired;
    if(error.length) {
      alert(error);
      return false;
    }
    return true;
  })
  
  var flashMenu = false;
  $('a.products').click(function(){
	discountMenu = false
	$('a.discount').removeClass('selected');
	
    flashMenu = !flashMenu;
    $("#flashMenu").get(0).showMenu("products",flashMenu);
    if(flashMenu) $(this).addClass('selected');
    else $(this).removeClass('selected');
    return false;
  });
  
  var discountMenu = false
  $('a.discount').click(function(){
	flashMenu = false
	$('a.products').removeClass('selected');
	
    discountMenu = !discountMenu;
    $("#flashMenu").get(0).showMenu("discount",discountMenu);
    if(discountMenu) $(this).addClass('selected');
    else $(this).removeClass('selected');
    return false;
  });
  
  // kereskedo kereses
  $('#dealer_search').click(function() {
	  var params = '';
	  var country = $('#dealers_country').val();
	  var state   = $('#dealers_state').val();
	  var city    = $('#dealers_city').val();
	  var name    = $('#dealers_name').val();
	  if (country != '') {
		  params += '/country/'+country;
	  }
	  if (state != '') {
		  params += '/state/'+state;
	  }
	  if (city != '') {
		  params += '/city/'+city;
	  }
	  if (name != '') {
		  params += '/name/'+name;
	  }
	  document.location.href = "/dealers"+params;
	  return false;
  });

  // Kereskedoink oldalon egymast kizaro keresesi lehetosegek biztositasa
  $('#dealers_country').focus(function() {
    $('#dealers_name').val('');
  });
  $('#dealers_state').focus(function() {
    $('#dealers_name').val('');
  });
  $('#dealers_state').change(function() {
    getCitiesToState($(this).val());
  });
  $('#dealers_country').change(function() {
    getStatesToCountry($(this).val());
  });
  $('#dealers_city').focus(function() {
    $('#dealers_name').val('');
  });
  $('#dealers_name').focus(function() {
    $('#dealers_country').val('');
    $('#dealers_state').val('');
    $('#dealers_city').val('');
  });
});

function getCitiesToState(stateSlug) {
  $.getJSON(
    '/getcities_to_state/'+stateSlug,
    function (data) {
      var options = '<option value="">'+dictionary.Varos+'</option>';
      for (var key in data) {
        options += '<option value="'+key+'">'+data[key]+'</option>';
      }
      $('#dealers_city').html(options);
    }
  );
}

function getStatesToCountry(countrySlug) {
  $.getJSON(
    '/getstates_to_country/'+countrySlug,
    function (data) {
      var options = '<option value="">'+dictionary.State+'</option>';
      for (var key in data) {
        options += '<option value="'+key+'">'+data[key]+'</option>';
      }
      $('#dealers_state')
        .html(options)
        .change();
    }
  );
}

function innerLabelInputIsEmpty($name, $form){
  var inp = $('input[name="'+$name+'"]', $form);
  return inp.val() == inp.attr('default') || inp.val().length == 0;
}

function loadCrawler(){
  var links = $("div.crawler a");
  $('div.subcrawlers div').eq(0).show();
  
  var $cnt = 0;
  links.each(function(){
    var $c = $cnt;
    $(this).hover(function(){
      $('div.subcrawlers div').hide();
      $('div.subcrawlers div').eq($c).show();
      //setContainerPosition()
    });
    $cnt++;
  });
  
  var selected_link = null;
  $('div.subcrawlers div').hover(function(){
	selected_link = $('a.selected',$(this));
	selected_link.removeClass('selected');
  },function(){
	selected_link.addClass('selected');
  })
}

function emailIsValid(email) {
  return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}

function fieldValue(name,form){
  var isinput = $('input[name="'+name+'"]',form).length;
  if(isinput)
	return $('input[name="'+name+'"]',form).val();
  else
    return $('select[name="'+name+'"] option:selected',form).val();
}

var RequestQueue = function() {
  this.queue = [];
  this.runingNow = false;
  
  this.add = function(callback) {
    this.queue.push(callback);
    this.execute();
    return this;
  };
  
  this.execute = function() {
    if (!this.runingNow && this.queue.length > 0) {
      this.runingNow = true;
      var last = this.queue.pop();
      this.queue = [];
      last();
    }
    return this;
  };
  
  this.done = function() {
    this.runingNow = false;
    return this.execute();
  };
};

var PIBSearch = function() {
  var self = this;
  
  this.searchBox = $('#PIBInputBox');
  this.layer = $('#search_results_layer').hide();
  this.resultLayer = $('.result', this.layer);
  this.defaultSearchBoxText = null;
  this.requestQueue = new RequestQueue();
  this.paneApi = $('.cont', this.layer).jScrollPane().data('jsp');
  
  $('.close', this.layer).click(function() {
    self.close();
    return false;
  });
  
  this.setDefaultSearcBoxtext = function(txt) {
    this.defaultSearchBoxText = txt;
    this.searchBox.val(this.defaultSearchBoxText);
    return this;
  };
  this.timeout = null;
  
  this.searchBox
    .keyup(function(e) {
      if (e.which == 13) {
        self.loadBox();
      } else if (e.which == 27) {
        self.searchBox.val('').blur();
      } else {
        self.setTimeout();
      }
    })
    .focus(function() {
      var $this = $(this);
      if ($this.val() == self.defaultSearchBoxText) {
        $this.val('');
      } else {
        self.layer.show();
      }
    })
    .blur(function() {
      var $this = $(this);
      if ($this.val() == '') {
        $this.val(self.defaultSearchBoxText);
        self.close();
      }
    });
  
  this.setTimeout = function() {
    var self = this;
    clearTimeout(this.timeout);
    this.timeout = setTimeout(function() {
      self.loadBox();
    }, 300);
  };
  
  this.loadBox = function() {
    var self = this;
    if (this.searchBox.val() == '') {
      this.close();
      return;
    }
    clearTimeout(this.timeout);
    this.requestQueue.add(function() {
      self.layer
        .show()
        .addClass('in-progress');
      self.resultLayer.load('/search_ajax', {'keywords': self.searchBox.val()},function(){
        self.layer.removeClass('in-progress');
        self.paneApi.reinitialise();
        self.requestQueue.done();
      });
    });
  };
  
  this.close = function() {
    clearTimeout(self.timeout);
    this.layer.hide();
  };
};

function objectLength(obj) {
  var cnt = 0;
  for (var i in obj) {
    cnt++;
  }
  return cnt;
}

var CustomSearch = function(selector) {
  this.baseNode = $(selector);
  this.boxContanier = $('.searchbox_right', this.baseNode);
  this.boxes = [];
  this.activeBox = -1;
  this.maxBoxCount = 5;
  this.resultWrapper = null;
  this.resultNode = null;
  var self = this;
  this.requestQueue = new RequestQueue();

  $('input[name="sort"]', this.baseNode).click(function() {
    self.start();
  });
  
  for (var i = 0; i < this.maxBoxCount; i++) {
    this.boxes[i] = new SearchBox(this, i);
  }
  
  this.start = function() {
    this.setActive(-1);
    this.makeRequest();
    return this;
  };
  
  this.setResultWrapper = function(resultWrapper) {
    this.resultWrapper = resultWrapper;
    return this;
  };
  this.setResultNode = function(resultNode) {
    this.resultNode = resultNode;
    return this;
  };

  this.getActiveBox = function() {
    if (this.boxes[this.activeBox]) {
      return this.boxes[this.activeBox];
    }
  };

  this.addBox = function(values, activeBox) {
    this.activeBox = activeBox;
    if (this.activeBox < this.maxBoxCount && objectLength(values) > 0) {
      this.getActiveBox().load(values);
    }
    return this;
  };

  this.setActive = function(index) {
    if (index < this.maxBoxCount-1) {
      this.boxes[index+1].empty();
    }
    for (var i = index+2; i < this.maxBoxCount; i++) {
      this.boxes[i].hide();
    }
    this.activeBox = index;
    if (this.activeBox < 0 || (this.activeBox == 0 && this.getActiveBox().getData().length == 0)) {
      this.resultNode.slideUp();
    } else {
      this.resultNode.slideDown();
    }
    return this.getActiveBox();
  }

  this.boxElementClick = function(box, id) {
    var active = this.setActive(box.index);
    if (active.getData().length == 0 && this.activeBox < this.maxBoxCount-1) {
      this.boxes[this.activeBox + 1].hide();
    } else {
      this.makeRequest();
    }
    return this;
  };
  
  this.makeRequest = function() {
    this.requestQueue.add(function() {
      var post = {};
      for (var i = 0; i <= self.activeBox; i++) {
        post["indexes[" + i + "][]"] = self.boxes[i].getData();
      }
      post.type = $('input[name="sort"]:checked', self.baseNode).val();
      $.post('/search_custom_ajax', post, function(data) {
        self.addBox(data.nextlist, data.listBoxIndex);
        self.resultWrapper.empty().empty().append(data.products);
        self.requestQueue.done();
      }, 'json');
    });
  };
};

var SearchBox = function(searchEngine, index) {
  this.searchEngine = searchEngine;

  this.node = $('<div/>')
    .attr({
      'class': 'filter_box' 
    });
  this.ul = $('<ul/>');
  this.searchEngine.boxContanier.append(this.node
    .append(this.ul)
    .hide()
  );
  this.index = index;

  var self = this;
  this.load = function(values) {
    this.empty();
    var cnt = 0;
    for (var id in values) {
      cnt++;
      var li = $('<li/>') 
        .click(function() {
          self.click(this);
          return false;
        });
      li.get(0).valueId = id;
      this.ul.append(li.append($('<a/>')
        .attr({href: '#'})
        .text(values[id])
      ));
    }
    if (index > 2 && cnt < 8) {
      this.node.addClass('small');
    } else {
      this.node.removeClass('small')
    }
    return this.show();
  };
  
  this.getData = function() {
    var data = [];
    $('li', this.ul).each(function(){
      if ($(this).hasClass('selected')) {
        data.push(this.valueId);
      }
    });
    return data;
  };
  
  this.empty = function() {
    this.ul.empty();
    return this;
  }

  this.show = function() {
    this.node.slideDown();
    return this;
  };
  
  this.hide = function() {
    this.node.slideUp();
    return this;
  };

  this.click = function(link) {
    $(link).toggleClass('selected');
    this.searchEngine.boxElementClick(this, link.valueId);
    return this;
  };
};

