function redirect(href) {
  window.location.href = href;
}


Event.observe(window, 'load', function() {
  /*
  items = document.getElementsByClassName('only_logged');
  
  for (var i = 0; i < items.length; i++) {
    items[i].hide();
  }
  */
  
  
  $('loginForm').onsubmit = function() {
    new Ajax.Request(
      BreezyCMS_URL + 'prihlaseni/login',
      {
        method: 'post',
        parameters: {login_name: $('login_form_login_name').value, login_password: $('login_form_login_password').value},
        onSuccess: function(transport)
        {
          response = transport.responseText;
          
          if (response == 'correct')
          {
            $('login_form_submit').submit();
            //window.location.href = BreezyCMS_URL;
          }
          else
          {
            alert('Login failed');
          }
        },
        onFailure: function(transport)
        {
          alert('Login failed');
        }
      }
    );
    
    return false;
  };
  
  $('loginAddItemForm').onsubmit = function() 
  {
    new Ajax.Request(
      BreezyCMS_URL + 'prihlaseni/login_add_item/' + lang,
      {
        method: 'post',
        parameters: {login_name: $('login_add_item_form_login_name').value, login_password: $('login_add_item_form_login_password').value,
                     product_id: $('product_id').value},
        onSuccess: function(transport)
        {
          response = transport.responseText;
          
          if (response == 'incorrect')
          {
            alert('Login failed');
          }
          else
          {
            items = document.getElementsByClassName('only_not_logged');
            
            for (var i = 0; i < items.length; i++) {
              $(items[i]).remove();
            }
            
            items = document.getElementsByClassName('only_logged');
  
            for (var i = 0; i < items.length; i++) {
              $(items[i]).removeClassName('only_logged');// = '';// show();
            }
            
            items = response.split('##');
            
            // vyprazdni form pro prihlaseni
            lightForm_erase();
            
            // aktualizuje kosik
            var inquiry = $('inquiry');
            inquiry.replace(items[0]);
            
            // zobrazi kosik
            lightForm('inquiry');
            
            // aktualizace uzivatelskeho menu
            $('subNav').replace(items[1]);
          }
        },
        onFailure: function(transport)
        {
          alert('Login failed');
        }
      }
    );
    
    return false;
  };
  
  /*
  $('basket_send').onclick = function() {
    
    new Ajax.Request(
      BreezyCMS_URL + 'basket/send/' + lang,
      {
        method: 'post',
        onSuccess: function(transport)
        {
          response = transport.responseText;

          if (response == 'done')
            redirect(window.location.href);
          else if (response == 'not-logged')
            alert('Nejste prihlasen.');
          else if (response == 'no-items')
            alert('Vas nakupni kosik je prazdny.');
          else
            alert('Objednavku se nepodarilo odeslat.');
        }
      });
      
    return false;
  }
  */
  
});

function basketSend()
{
  new Ajax.Request(
    BreezyCMS_URL + 'basket/send/' + lang,
    {
      method: 'post',
      onSuccess: function(transport)
      {
        response = transport.responseText;

        if (response == 'done')
          redirect(window.location.href);
        else if (response == 'not-logged')
          alert('Nejste prihlasen.');
        else if (response == 'no-items')
          alert('Vas nakupni kosik je prazdny.');
        else
          alert('Objednavku se nepodarilo odeslat.');
      }
    });
    
  return false;
}

function buyItem(id)
{
  new Ajax.Request(
    BreezyCMS_URL + 'basket/add_item/' + id + '/' + lang,
    {
      method: 'get',
      onSuccess: function(transport)
      {
        response = transport.responseText;
        
        if (response == 'not-logged')
        {
          $('product_id').value = id;
          lightForm('loginAddItemForm');
        }
        else
        {
          var inquiry = $('inquiry');

          inquiry.replace(response);
          lightForm('inquiry');
        }
      },
      onFailure: function(transport)
      {
        alert('Buy item failed');
      }
    }
  );
}

function removeItem(a, id)
{
  //$(a.parentNode.parentNode).hide();
  
  new Ajax.Request(
    BreezyCMS_URL + 'basket/remove_item/' + id + '/' + lang,
    {
      method: 'get',
      onSuccess: function(transport)
      {
        response = transport.responseText;
        
        
        $('inquiry').replace(response);
        //alert(response);
        $('inquiry').show();
      }
    }
  );
}

//Foot resizing handle
function updateMainPadding()
{
  $('main').style.paddingBottom = ($('foot').getHeight() + 41) + 'px';
}

//Language selector replace
Autocompleter.SelectBox = Class.create();
Autocompleter.SelectBox.prototype = Object.extend(new Autocompleter.Base(), {
  initialize: function(select, options) {
	this.element = "<input type=\"text\" id=\"" + $(select).id + "_combo\" />"
	new Insertion.Before(select, this.element)
	var inputClasses = Element.classNames(select);
	
	this.update = "<div id=\"" + $(select).id + "_options\" class=\"" + inputClasses + "\"></div>"	
	new Insertion.Before(select, this.update)
	
  this.baseInitialize($(select).id + "_combo", $(select).id + "_options", options);
  this.select = select;
	this.selectOptions = [];
		
	$(this.element.id).setAttribute('readonly','readonly');
	this.element.readOnly = true;
	
	Element.hide(select);
	Element.addClassName(this.element.id, 'select') ;
	
	var optionList = $(this.select).getElementsByTagName('option');
	var nodes = $A(optionList);

	for(i=0; i<nodes.length;i++){
    if (nodes[i].getAttribute("selected")) this.element.value = nodes[i].innerHTML;
    else this.selectOptions.push("<li id=\"" + nodes[i].value + "\" onmouseover=\"this.className='hover';\" onmouseout=\"this.className='';\">" + nodes[i].innerHTML + '</li>');

    /*
		this.selectOptions.push("<li id=\"" + nodes[i].value + "\" onmouseover=\"this.className='hover';\" onmouseout=\"this.className='';\">" + nodes[i].innerHTML + '</li>');
		if (nodes[i].getAttribute("selected")) this.element.value = nodes[i].innerHTML;
    */
	}
	
	Event.observe(this.element, "click", this.activate.bindAsEventListener(this));
	
	if ($(select).selectedIndex >= 0)this.element.value = $(select).options[$(select).selectedIndex].innerHTML;
	
	var self = this;
	this.options.afterUpdateElement = function(text, li) {
		var optionList = $(select).getElementsByTagName('option');
		var nodes = $A(optionList);

		var opt = nodes.find( function(node){
			return (node.value == li.id);
		});
		$(select).selectedIndex=opt.index;

		$('langSelectForm').submit();
	}
  },

  getUpdatedChoices: function() {
  		this.updateChoices(this.setValues());
  },

  setValues : function(){
		return ("<ul>" + this.selectOptions.join('') + "</ul>");
  },
  
  setOptions: function(options) {
    this.options = Object.extend({
		css			: 'select'	 //css class for new element 
	}, options || {});
  }
});

Event.observe(window, 'load', function() {
  new Autocompleter.SelectBox('langSelect');
  	
	//Gallery sliding prepare
	var gallerySliding = $$('div#gallery div.sliding');
	if (gallerySliding.length)
	{
	  gallerySliding = gallerySliding[0];
	  gallerySliding.update('<div>' + gallerySliding.innerHTML + '</div>');
	  gallerySliding.style.width = gallerySliding.firstDescendant().getWidth() + 'px';
	}
	
	updateMainPadding();
	
	//Colored main navigation background handling 
  var navBg = $('navBg');
  var activeBtn = $$('#nav li.active');
  activeBtn = (typeof(activeBtn[0]) != 'undefined') ? activeBtn[0] : null;
	var initPos = activeBtn ? activeBtn.positionedOffset() : null;
	var initWidth = activeBtn ? activeBtn.getWidth() : 0;
	var prevNavHover, cachePrevNavHover, fadeEffect;
	
	if (activeBtn)
	{
	  navBg.style.width = initWidth + 'px';
  	navBg.style.left = initPos.left + 'px';
    navBg.style.top = initPos.top + 'px';
    
    Event.observe(window, 'resize', function() {
      initPos = activeBtn.positionedOffset();
      navBg.style.left = initPos.left + 'px';
      navBg.style.top = initPos.top + 'px';
	  });
  }
	
	var buttons = $('nav').childElements();
	for(var i = 0; i < buttons.length; i++) {
	  var link = buttons[i].firstDescendant();
	  link.onmouseover = function()
	  {
		  if (prevNavHover != this)
			{
        if (activeBtn)
        {
				  if (this.parentNode != activeBtn) activeBtn.firstDescendant().addClassName('noActive');
			    else activeBtn.firstDescendant().removeClassName('noActive');
				}
	      else if (!prevNavHover) {
	        prevNavHover = this;
	        var pos = this.parentNode.positionedOffset();
	        navBg.style.width = this.parentNode.getWidth() + 'px';
	        navBg.style.left = pos.left + 'px';
	        navBg.style.top = pos.top + 'px';
	        if (typeof(fadeEffect) != 'undefined') fadeEffect.cancel();
	        navBg.setOpacity(1);
	        navBg.show();
	        return;
			  }
        
				prevNavHover = this;
			  new Effect.Morph('navBg', {style: 'width: ' + this.parentNode.getWidth() + 'px; left: ' + this.parentNode.positionedOffset().left + 'px;', duration: 0.3});
			}
		}
			
		link.onmouseout = function()
	  {
	    cachePrevNavHover = prevNavHover;
	    window.setTimeout(function() {
	      if (prevNavHover != cachePrevNavHover) return;
	      prevNavHover = activeBtn ? activeBtn.firstDescendant() : null;
	      
	      if(activeBtn)
	      {
	        activeLink = activeBtn.firstDescendant();
	        activeLink.removeClassName('noActive');
		      new Effect.Morph('navBg', {style: 'width: ' + initWidth + 'px; left: ' + initPos.left + 'px;', duration: 0.3});
		    }
		    else fadeEffect = new Effect.Fade(navBg, { duration: 0.2 });
		  }, 150);
		}
	}
	
	var slideClothes = $('slideClothes');
	var slideClothesEffect;
	var slideClothesDirection = 0;
	if (slideClothes)
	{
	  var slideClothes_inner = slideClothes.firstDescendant();
	  
	  slideClothes.onmouseout = function()
	  {
	    slideClothesDirection = 0;
	    if (typeof(slideClothesEffect) != 'undefined') slideClothesEffect.cancel();
		  var w = document.viewport.getWidth();
		  slideClothesEffect = new Effect.Move(slideClothes_inner, { x: -((slideClothes_inner.getWidth() - w) / 2), y: 0, mode: 'absolute', transition: Effect.Transitions.customSpring, duration: 3});
		}
	  
	  slideClothes.onmousemove = function(e)
	  {
	    var mPos = Event.pointerX(e);
	    var w = document.viewport.getWidth();
	    var tempSlideClothesDirection = mPos > w / 2 ? -1 : 1;
			if (tempSlideClothesDirection == slideClothesDirection) return;
	    slideClothesDirection = tempSlideClothesDirection;
	    
	    if (typeof(slideClothesEffect) != 'undefined') slideClothesEffect.cancel();
	    slideClothesEffect = new Effect.Move(slideClothes_inner, { x: slideClothesDirection == 1 ? 0 : -slideClothes_inner.getWidth() + w, y: 0, mode: 'absolute', transition: Effect.Transitions.exponencial, duration: 3 });
		}
		
		Event.observe(window, 'resize', function()
		{
		  var w = document.viewport.getWidth();
			slideClothes.style.width = (w < 960 ? 960 : w) + 'px';
		  slideClothes_inner.style.left = -((slideClothes_inner.getWidth() - w) / 2) + 'px';
		});
	}
});

//FAQ opening and closing
function faq_open(el)
{
  el.onclick = function() { return false;};
  el = $(el);
  
	if ($(el.parentNode).getStyle('overflow') == 'hidden')
	{
	  var next = el.next();
		next.style.height = next.getHeight() + 'px';
		next.style.display = 'none'; 
	  el.parentNode.style.overflow = 'visible';
	  el.parentNode.style.height = 'auto';
	}
  
  var others = $$('#faq li.active');
  if (others.length)
  {
	  Effect.BlindUp(others[0].childElements().last(), { duration: 0.2, afterFinish: function(effect) {
		  $(effect.element.parentNode).removeClassName('active');
		  $(el.parentNode).addClassName('active');
      Effect.BlindDown(el.next(), { duration: 0.2, afterFinish: function(effect) {
	      $(effect.element.parentNode).firstDescendant().onclick = function() {faq_close(this); return false;};
	    } });
		} });
		return;
	}
	
  $(el.parentNode).addClassName('active');
  Effect.BlindDown(el.next(), { duration: 0.2, scaleContent: false, afterFinish: function(effect) {
	  $(effect.element.parentNode).firstDescendant().onclick = function() {faq_close(this); return false;};
	} });
}

function faq_close(el)
{
  el.onclick = function() { return false;};
  Effect.BlindUp($(el).next(), { duration: 0.2, afterFinish: function(effect) {
    var parent = $(effect.element.parentNode); 
	  parent.removeClassName('active');
	  parent.firstDescendant().onclick = function() {faq_open(this); return false;};
	} });
}

function gallery_scroll(direction)
{
  direction = (direction == 'left' ? 1 : -1);
  var wrap = $('gallery');
  var sliding = wrap.firstDescendant();
  var sWidth = sliding.getWidth();
	var offset = 644;
	
	if (sWidth < offset) return;
	
	if (direction == 1 && (!sliding.style.left || sliding.style.left == '0px'))
	{
	  direction = -1;
	  offset = sWidth - offset;
	}
	else if (direction == -1 && sliding.style.left == (-sWidth + offset) + 'px')
	{
	  direction = 1;
	  offset = sWidth - offset;
	}
	else {
	  var pos = parseInt(sliding.style.left.substring(0, sliding.style.left.length-2));
	  if (pos)
	  {
		  if (direction == -1 && pos - offset + sWidth < offset) offset = pos - offset + sWidth; 
		  else if (direction == 1 && pos + offset > 0) offset = -pos;
		}
	}
	 
  new Effect.Move(sliding, { x: direction * offset, y: 0, mode: 'relative' });
}

function switchFooter(type, el)
{
  var mainWrap = $('footWraps');
  var wraps = mainWrap.firstDescendant().firstDescendant().childElements();
	el = $(el);
	
  if (el.hasClassName('active'))
  {
	  el.removeClassName('active');
	  Effect.SlideUp(mainWrap, { afterFinish: function() {$('foot_'+type).hide(); updateMainPadding(); } }); 
	}
	else
	{
	  var btns = $('footNav').childElements();
	  for(var i = 0; i < btns.length; i++) {
		  btns[i].firstDescendant().removeClassName('active');
		}
	  el.addClassName('active');
	  
	  var opened;
	  for(var i = 0; i < wraps.length; i++) {
		  if (wraps[i].visible())
		  {
		    opened = wraps[i];
			  break;
			}
		}
		if (opened)
		{
		  Effect.BlindUp(mainWrap, { afterFinish: function() {
		    opened.hide();
		    $('foot_'+type).show();
			  Effect.BlindDown(mainWrap, { afterFinish: function() { updateMainPadding(); window.scrollTo(document.viewport.getScrollOffsets().left, 100000); } });
			} });
		}
		else
		{
		  $('foot_'+type).show();
		  Effect.BlindDown(mainWrap, { afterFinish: function() { updateMainPadding(); window.scrollTo(document.viewport.getScrollOffsets().left, 100000); } });
		}
	}
}

function lightForm(el)
{
  var padding = 50;
  el = $(el);
  var body = $(document.body);
  var vpSize = document.viewport.getDimensions();
  var vpOffset = document.viewport.getScrollOffsets();
  var wrapWidth = el.getWidth() + padding;
  var wrapWidth = 640;
  
  body.insert('<span id="lightForm_overlay" style="display: none;" onclick="lightForm_close();">&nbsp</span>');
  var overlay = $('lightForm_overlay');
  
  body.insert('<div id="lightForm" style="width: ' + wrapWidth + 'px; display: none;"><div class="lightFormContent"><div class="top"><span></span></div><div id="inside"></div><div class="bottom"><span></span></div></div></div>');
	var wrap = $('lightForm');
  var wrap2 = $('inside');
  
	//wrap.insert(el.remove().show());
  wrap2.insert(el.remove().show());
	var wrapHeight = wrap.getHeight();
	
	var heightB = body.getHeight();
	if (heightB < wrapHeight + vpOffset.top + padding) heightB = wrapHeight + vpOffset.top + padding;
	
	overlay.style.height = (heightB > vpSize.height ? heightB : vpSize.height) + 'px';
  overlay.style.width = vpSize.width + 'px';
	
	wrap.style.left = ((vpSize.width - wrapWidth) / 2 + vpOffset.left) + 'px';
	
	wrap.style.top = (vpOffset.top + (wrapHeight > vpSize.height + 60 ? 30 : (vpSize.height - wrapHeight) / 2)) + 'px';
	
  
  Effect.Appear(overlay, { to: 0.8, duration: 0.5 });
  Effect.Appear(wrap, { duration: 0.5 });
}

function lightForm_close()
{
  var overlay = $('lightForm_overlay');
  var wrap = $('lightForm');
  var wrap2 = $('inside');
  Effect.Fade('lightForm_overlay', { duration: 0.5 });
  Effect.Fade(wrap, { duration: 0.5, afterFinish: function()
	  {
	    var childs = wrap2.childElements();
	    var body = $(document.body);
	    for (var i = 0; i < childs.length; i++) {
			  childs[i].hide();
			  body.insert(childs[i].remove());
			}
			wrap.remove();
			overlay.remove();
	  }
	});
}

function lightForm_erase()
{
  var wrap = $('lightForm');
  
  var childs = wrap.childElements();
  var body = $(document.body);
  for (var i = 0; i < childs.length; i++) {
    childs[i].hide();
    body.insert(childs[i].remove());
  }
}

