var gallery;

var Gallery = function(list) {
  this.photos = $$('#' + $(list).identify() + ' img');
  this.background = $(document.createElement('div'));
  this.background.setStyle({
    display: 'none',
    position: 'absolute',
    top: '0',
    left: '0',
    background: 'black',
    opacity: '0.5'
  });
  this.background.observe('click',(function(){ this.close() }).bind(this));
  this.container = $(document.createElement('div'));
  this.container.setStyle({
    display: 'none',
    position: 'absolute',
    top: '0',
    left: '0',
    padding: '10px',
    background: 'white',
    border: '1px solid silver'
  });
  this.container.parentGallery = this;
  this.container.innerHTML = '<p align="right"><a style="color:black" href="#" onclick="this.parentNode.parentNode.parentGallery.close();return false" class="gal_close"></a></p>' +
  '<div style="position:relative"><img src="' + this.photos[0].src.replace('_th200','') +
  '" onclick="this.parentNode.parentNode.parentGallery.next();return false" />' +
  '<a style="position:absolute;top:80px;left:0;text-decoration:none;font-weight:bold;font-size:30px;color:black" href="#" class="gal_left" onclick="this.parentNode.parentNode.parentGallery.prev();return false"></a>' +
  '<a style="position:absolute;top:80px;right:0;text-decoration:none;font-weight:bold;font-size:30px;color:black" href="#" class="gal_right" onclick="this.parentNode.parentNode.parentGallery.next();return false"></a>' +
  '</div><center>' + this.photos[0].title + '</center>';
  document.body.appendChild(this.background);
  document.body.appendChild(this.container);
  this.image = $(this.container.childNodes[1].firstChild);
  this.image.observe('load',(function() {
    var temp = new Image();
    temp.src = this.image.src;
    this.image.removeAttribute('height');
    this.image.originalHeight = temp.height || this.image.height;
    this.photos.each((function(e,i){ if(e.src.replace('_th200','') == this.image.src) this.actualPhoto = i; }).bind(this));
    if(this.container.style.display != 'none') this.show();
  }).bind(this));
  window.setInterval((function(){ if(this.container.style.display != 'none') this.show(); }).bind(this),500);

  this.show = (function(src) {
    $$('embed,object').invoke('hide');
    var viewWidth = $(document).viewport.getWidth();
    var viewHeight = $(document).viewport.getHeight();
    if(this.image.originalHeight > viewHeight - 50) {
      this.image.height = viewHeight - 50;
    } else {
      this.image.height = this.image.originalHeight;
    }
    var height = this.container.getHeight();

    this.background.setStyle({
      display: 'block',
      width: $(document.body).getWidth() + 'px',
      height: $(document.body).getHeight() + 'px'
    });
    var top = parseInt((viewHeight - height)/2);

    if(src) this.image.src = src;

    this.container.setStyle({
      display: 'block',
      left: parseInt((viewWidth - this.container.getWidth())/2)+'px',
      top: ((top > 0)?top:0)+'px'
    });
  }).bind(this);
  this.close = (function() {
    this.background.hide();
    this.container.hide();
    $$('embed,object').invoke('show');
  }).bind(this);
  this.next = function() {
    if(this.actualPhoto == this.photos.length - 1) this.actualPhoto = -1;
    this.image.src = this.photos[++this.actualPhoto].src.replace('_th200','');
    this.container.lastChild.innerHTML = this.photos[this.actualPhoto].title;
  }.bind(this);
  this.prev = function() {
    if(this.actualPhoto == 0) this.actualPhoto = this.photos.length;
    this.image.src = this.photos[--this.actualPhoto].src.replace('_th200','');
    this.container.lastChild.innerHTML = this.photos[this.actualPhoto].title;
  }.bind(this);
}

function home() {
  $$('.btn_search').invoke('observe','click',function(e) {
    var loc = e.element().href;
    var type = $('type').value;
    var sale = $$('input[name=sale]')[0];
    var price_from = parseInt($$('input[name=price_from]')[0].value);
    var price_to = parseInt($$('input[name=price_to]')[0].value);

    if(type) loc += type + '/';
    loc += (sale && sale.value == 2) ? 'pronajem/' : 'prodej/';
    if(!isNaN(price_from) || !isNaN(price_to)) loc += (isNaN(price_from) ? ('cena-0-' + price_to) : ('cena-' + price_from + '-' + price_to)) + '/';
    location = loc + 'text-' + $$('input[name=text]')[0].value;
    e.stop();
  });

  var showRange = function(start, end) {
	$$('#scroll li').each(function(e, i) { if (i < start || i > end) e.hide(); else e.show(); });
  }

  var start = 0;
  $$('#scroll .fl')[0].observe('click',function(e) {
	if (start < 1) start = 1;
	showRange((--start), start + 3);
	if (start < 1) {
		disable(this);
	} else {
		enable(this);
	}
	enable($$('#scroll .fr')[0]);
    e.stop();
  });
  $$('#scroll .fr')[0].observe('click',function(e) {
    limit = $$('#scroll img').length;

	if (start > limit - 5) start = limit - 5;
	showRange((++start), start + 3);
    e.stop();
    if (start > limit - 5) {
		disable(this);
	} else {
		enable(this);
	}
	enable($$('#scroll .fl')[0]);
  });

  showRange(0,3);
}

function disable(el) {
    el.addClassName('disabled');
}

function enable(el) {
    el.removeClassName('disabled');
}

function detail() {
  var from = 0,to = 2,images = $$('#gallery li');
  var nextBt = $$('#gallery .next')[0];
  var prevBt = $$('#gallery .prev')[0];

  function showImages(from,to) {
    images.each(function(e,i){ if(i < from || i > to) e.hide(); else e.show() });
  }
  function next(e) {
    if(from > images.length - 4) {
      nextBt.setStyle({ visibility: 'hidden' });
      e.stop();
	  return;
    }
    prevBt.setStyle({ visibility: 'visible' });
    showImages(++from,++to);
    e.stop();
  }
  function prev(e) {
    if(from < 1) {
      prevBt.setStyle({ visibility: 'hidden' });
      e.stop();
	  return;
    }
    nextBt.setStyle({ visibility: 'visible' });
    showImages(--from,--to);
	e.stop();
  }

  if($('gallery')) {
    gallery = new Gallery('gallery');
    $('big_image').observe('click',function(e){ gallery.show(e.element().src) });
    gallery.photos.invoke('observe','click',function(e){ $('big_image').src = e.element().src.replace('_th200',''); e.stop() });
    $('gallery').down('ul').setStyle({ overflow: 'hidden' });
    nextBt.observe('click',next);
    prevBt.observe('click',prev);
    if(images.length > 3) nextBt.setStyle({ visibility: 'visible' });
    $('lenght').update(images.length);
    $('lenght').innerHTML;
    for(var i=1; i <= images.length; i++) {
    	$('img'+i).observe('click', getImgNum);
	}
    showImages(0,2);
  }
}

function getImgNum(event) {
  	var element = event.element(event).id;
  	element = element.substring(3);
  	$('num').update(element);
	$('num').innerHTML;
}

function addToFavourites(id) {

}

function addFile(element) {
  var e = $(element);
  var file = $(document.createElement('input'));
  file.type = 'file';
  file.name = 'file_' + file.identify();
  element.appendChild(file.wrap('p'));
}

function list() {
  $('ul_kraje').observe('click',function(e) {
    var el = e.element();
    if(el.tagName.toLowerCase() == 'input') {
      $(el.id + '_okresy_dt').toggle();
      $(el.id + '_okresy').toggle();
    }
  });
  $$('.okresy').each(function(e){ if(!$(e.id.replace('_okresy','').replace('_dt','')).checked) e.hide() });
  $$('.vypis')[0].observe('click',function(e) {
    el = e.element();
    if(el.hasClassName('fav')) {

    } else if(el.hasClassName('sel')) {
      new Ajax.Request('/?w=ajax&action=add_for_print&id=' + el.name.substr(2));
    } else if(el.up('.item')) {
	  location = el.up('.item').down('a').href;
	}
  });

}

function cleanPrintList() {
  $$('.vypis .sel').each(function(e){ e.checked = false });
  new Ajax.Request('?w=ajax&action=clean_print_list');
}

function valid() {
	if($('text').value == 'Např. u lesa, Modřany ...') $('text').value = '';
	return true;
}

function tabs() {
  var lastHash = '';

  setInterval(function() {
	var hash = location.hash.toString();

	if (hash && hash != lastHash) {
	  $$('.sekce').invoke('hide');
	  ($(hash.substr(1).replace('-', '_')) || $('o_projektu')).setStyle({ display: 'block' });

	  lastHash = hash;

	  $$('#detail_menu a').each(function(e) {
		if (e.href.endsWith(lastHash)) {
		  e.addClassName('active');
		} else {
		  e.removeClassName('active');
		}
	  })
	}
  }, 250);
}

function toggleVisible(element) {
  element.setStyle({ visibility: (element.getStyle('visibility') == 'hidden') ? 'visible' : 'hidden' });
}

function showHide() {
	if($$('.podrobny_filtr')[0].getStyle('display') == 'none') {
		$$('.podrobny_filtr')[0].show();
		$$('.search_adv')[0].update('Zavřít rozšířené hledání');
	} else {
		$$('.podrobny_filtr')[0].hide();
		$$('.search_adv')[0].update('Rozšířené hledání »');
	}
	$$('#find *').each(function(e) { if(e.className != 'search_adv') toggleVisible(e) });
}

function ajax_select(eid) {
	new Ajax.Request('/include/ajax.php', {
		method: 'get',
		parameters: {id: eid, action: 'true'},
		onSuccess: function(transport) {
		    var response = transport.responseText;

			$$('.sel').each(function(e) {
			  if (e.checked) {
				e.up('.item').addClassName('selected');
			  } else {
				e.up('.item').removeClassName('selected');
			  }
			});
		},
		onFailure: function(){  }
	});
}

document.observe('dom:loaded',function() {
  if($('scroll')) home();
  if($$('.vypis')[0]) list();
  if($('gallery')) detail();
  if($('detail_menu')) tabs();
  if($('text')) {
    if(!$('text').value) {
		$('text').value = 'Např. u lesa, Modřany ...';
	}
  }
  $$('.hypoteka')[0].observe('click', function(e) {
	$$('.hypoteka')[0].writeAttribute('target', '_blank');
  });
  var links = $$('#main_menu ul a');
  var menuWidth;
  var size;

  do {
	size = parseInt(links[0].getStyle('fontSize').replace('px',''));

	menuWidth = 0;
    links.each(function(e) { menuWidth += e.getWidth() });
    links.invoke('setStyle',{ fontSize: (size - 1) + 'px' });
  } while(menuWidth > 730);

  $(document).observe('keypress', function(e) {
	if (e.element().tagName.toLowerCase() != 'textarea' && e.keyCode == 13) {
	  var el = e.element();

	  if (el.type && el.up('form')) {
		el.up('form').submit();
	  }
	}
  });
})

