KeyCode = {};
KeyCode.isControl = function(code) {
	var i, controlCodes = [8,9,13,16,17,18,19,20,27,33,35,36,37,38,39,40,45,46,144,145];
	for (i = 0 ; i < controlCodes.length ; i++) {
		if (code == controlCodes[i]) {
			return true;
		}
	}
	
	return false;
}
String.prototype.isPostCode = function(length) {
	var c,
		self = this,
		l = self.length;

	length = length || 6;	
	if (l != length || l > 6) {
		return false;
	}
	
	if (l > 0) {
		c = self.charAt(0);
		if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
			return false;
		}
		if (l > 1) {
			c = self.charAt(1);
			if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
				return false;
			}
			if (l > 2) {
				c = self.charAt(2);
				if (c != '-') {
					return false;
				}
				if (l > 3) {
					c = self.charAt(3);
					if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
						return false;
					}
					if (l > 4) {
						c = self.charAt(4);
						if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
							return false;
						}
						if (l > 5) {
							c = self.charAt(5);
							if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
								return false;
							}
						}
					}
				}
			}
		}
	}
	
	return true;
}

jQuery.fn.caret = function(params) {
	var self = this,
		elem = self[0],
		selectionRange,
		start,
		end;

	if (typeof elem.selectionStart != 'undefined') {
		return {'start': elem.selectionStart, 'end': elem.selectionEnd};
	} else if (document.selection) {
		selectionRange = document.selection.createRange();

		return {'start': selectionRange.offsetLeft - 1, 'end': selectionRange.offsetLeft + selectionRange.text.length - 1};
	}	
	return {'start': -1, 'end': -1};
}

jQuery.fn.clear = function(params) {
	$(this).each(function() {
		var self = $(this),
			tag = self[0].tagName.toLowerCase(),
			type = self.attr('type');

		if (tag == 'input') {
			switch (type) {
			case 'checkbox':
			case 'radio':
				self.attr('checked', false);
				break;
			default:
				if (self.attr('default')) {
					self.val(self.attr('default'));
				} else {
					self.val('');
				}
			}
		}
		if (tag == 'select') {
			self.find('option:first-child').attr('selected', 'selected');
		}
	});
}
jQuery.fn.defaultValue = function(value, cssDefault, cssNormal) {
	var self = $(this), dV = value;
	self.attr('default', dV);
	if (!self.val()) {
		self.val(dV);
		if (typeof cssDefault != 'undefined') {
			self.css(cssDefault);
		}
	}
	self.change(function() {
		if (!self.val()) {
			self.val(dV);
			if (typeof cssDefault != 'undefined') {
				self.css(cssDefault);
			}
		}
	});
	self.focusin(function() {
		if (self.val() == dV) {
			self.val('');
			if (typeof cssDefault != 'undefined') {
				self.css(cssNormal);
			}
		}
	});
	self.focusout(function() {
		if (!self.val()) {
			self.val(dV);
			if (typeof cssDefault != 'undefined') {
				self.css(cssDefault);
			}
		}
	});
}

jQuery.fn.limitLineWidth = function(options) {
	$(this).each(function() {
		var self = $(this),
			s = self.html(),
			l = s.length,
			i;
		for (i = l - 1 ; i >= 0 && self.width() > options.width; self.html(s.substr(0, i--) + '...'));
	});
}
jQuery.fn.validInput = function(options) {
	$(this).each(function() {
		var self = $(this),
			type = options.type,
			s;

		switch (type) {
			case 'post_code':
				self.keypress(function(event) {
					var range,
						keyCode = event.keyCode > 0 ? event.keyCode : event.charCode,
						s;
					if (!(KeyCode.isControl(keyCode) || (keyCode >= 48 && keyCode <= 57) || keyCode == 45)) {
						event.preventDefault(); 
						
						return false;
					}

					s = self.val();
					range = self.caret();

					if (!KeyCode.isControl(keyCode)) {
						s = s.substr(0, range.start) + (keyCode == 45 ? '-' : String.fromCharCode(keyCode)) + s.substr(range.end);

						if (!s.isPostCode(s.length)) {
							event.preventDefault();

							return false;
						}
					}
				});
				self.keyup(function(event) {
					var keyCode = event.keyCode > 0 ? event.keyCode : event.charCode,
						p;
					
					s = self.val();
					for (p = s.indexOf('\'') ; p != -1 ; p = s.indexOf('\'')) {
						s = s.substr(0, p) + s.substr(p + 1);
					}
					for (p = s.indexOf('.') ; p != -1 ; p = s.indexOf('.')) {
						s = s.substr(0, p) + s.substr(p + 1);
					}
					self.val(s);
					
					if (keyCode != 8 && keyCode != 46 &&  s.length == 2 && s.isPostCode(2)) {
						self.val(s + '-');
					}
				});
				break;
			case 'positive_integer':
				self.keypress(function(event) {
					var keyCode = event.keyCode > 0 ? event.keyCode : event.charCode;
										
					if (!KeyCode.isControl(keyCode) && (keyCode < 48 || keyCode > 57)) {
						event.preventDefault(); 

						return false;
					}
				});
				break;
		}
	});
}
jQuery.fn.toggleOverflow = function(opts) {
	$(this).each(function() {
		var self = $(this),
			options = opts,
			id = $(this).attr('id') ? $(this).attr('id') : Math.ceil(Math.random() * 1000),
			oldHeight,
			newHeight,
			button,
			up = true;
		
		oldHeight = self.height();		
		newHeight = self.children().first().height();		
		self.css({
			'height' : self.height() + 'px',
			'overflow' : 'hidden'
		});
		self.parent().css({
			'position': 'absolute'
		});
		self.parent().parent().append('<div id="' + id + '_fake"></div>');
		if (oldHeight < newHeight) {
			self.parent().append('<div id="' + id + '_button" class="overflowDownButton"></div>');
			div = $('#' + id  + '_button');
			self.parent().mouseleave(function() {
				if (!up) {
					self.animate({
						'height' : oldHeight + 'px'
					}, 500, function() {
						div.attr('class', 'overflowDownButton')
					});
					up = true;
				}
			});
			div.click(function() {
				if (up) {
					self.animate({
						'height' : newHeight + 'px'
					}, 500, function() {
						div.attr('class', 'overflowUpButton')
					});
					up = false;
				} else {
					self.animate({
						'height' : oldHeight + 'px'
					}, 500, function() {
						div.attr('class', 'overflowDownButton')
					});
					up = true;
				}
			});
		} else {
			self.parent().append('<div id="' + id + '_button" class="overflowNoneButton"></div>');
			self.css({'height' : newHeight});
			div = $('#' + id  + '_button');
		}
		$('#' + id  + '_fake').css({
			'height': self.parent().height() + 'px'
		});
	});
}
jQuery.fn.centerElement = function() {
	$(this).each(function() {
		var self = $(this),
		parent = self.parent(),
		pw = parent.width(),
		ph = parent.height(),
		w = self.outerWidth(),
		h = self.outerHeight();
		self.css({
			'margin-left': Math.floor((pw-w)/2),
			'margin-right': Math.ceil((pw-w)/2),
			'margin-top': Math.floor((ph-h)/2),
			'margin-bottom': Math.ceil((ph-h)/2)
		});
	});
}

/**
 * $('img.photo',this).imagesLoaded(myFunction)
 * execute a callback when all images have loaded.
 * needed because .load() doesn't work on cached images
 * src: https://gist.github.com/268257
 * timout na frame'a
 */
$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load.imgloaded',function(){
      if (--len <= 0 && this.src !== blank){ 
        elems.unbind('load.imgloaded');
        callback.call(elems,this); 
      }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }  
  }); 

  return this;
};
$.fn.cardGallerySlider2 = function() {
  return this.each(function() {
    var root = $(this);
    var arrowLeft = root.find('.arrowLeft');
    var arrowRight = root.find('.arrowRight');
    var holder = root.find('.content');
    var holderWidth = holder.width();
    var slider = holder.find('ul');
    var images = holder.find('img');
    var imagesWidth = 0;
    var interval;
    
    var onArrowEnter = function() {
      var arrow = $(this);
      var sliderWidth = slider.outerWidth();
      var speed = arrow.hasClass('arrowLeft') ? 10 : -10;
      var value = parseInt(slider.css('margin-left'), 10);
      interval = setInterval(function() {
        value = speed + value;
        if (-value > 0 && -value < sliderWidth - holderWidth) {
          slider.css('margin-left', value);
        }
      }, 40);
    };
    
    var onArrowLeave = function() {
      clearInterval(interval);
    };
    
    var onImagesLoaded = function() {
      images.each(function() {
        var img = $(this);
        var width = img.width();
        var height = img.height();
        var li = img.parents('li');
        li.width(img.outerWidth());
        imagesWidth += li.outerWidth();
        holder.css('visibility', 'visible');
        img.bind({
          'mouseenter': function() {
            img = $(this);
            img.height(88);
            img.css({
              'margin-top': - (88 - height) / 2,
              'margin-left': - (img.width() - width) / 2
            });
          },
          'mouseleave': function() {
            img = $(this);
            img.height(height);
            img.css({
              'margin-top': 0,
              'margin-left': 0
            });
          }
        });
      });
      
      slider.width(imagesWidth);
      
      if (slider.outerWidth() > holderWidth) {
        arrowLeft.css('visibility', 'visible').bind({
          'mouseenter': onArrowEnter,
          'mouseleave': onArrowLeave
        });
        arrowRight.css('visibility', 'visible').bind({
          'mouseenter': onArrowEnter,
          'mouseleave': onArrowLeave
        });
      } else {
        slider.css('margin-left', holderWidth / 2 - slider.outerWidth() / 2)
      }
    };
    
    var onImagesLoadedIframe = function() {
      setTimeout(onImagesLoaded, 700);
    };
    

    var callback = (top!==self) ? onImagesLoadedIframe : onImagesLoaded;
    images.imagesLoaded(callback);
  });
};

/**
 * simple accordion
 */
$.fn.accord = function(options) {
  options = $.extend({
    triggerSelector: '.trigger',
    textSelector: '.text',
    expandedClass: 'expanded'
  }, options);
  var items = this, 
      ts = options.textSelector,
      cl = options.expandedClass;
      
  return items.each(function() {
    var item = $(this);
    item.delegate(options.triggerSelector, 'click', function(event) {
      event.preventDefault();
      var expanded = items.filter('.' + cl);
      if (item[0] !== expanded[0]) {
        expanded.find(ts).slideUp('fast', function() {
          expanded.toggleClass(cl);
        });
        item.find(ts).slideDown('fast', function() {
          item.toggleClass(cl);
        });
      } else {
        item.find(ts).slideUp('fast', function() {
          item.toggleClass(cl);
        });
      }
    });
  });
};

$.fn.cardGallerySlider = function() {
  $(this).each(function() {
    var self = $(this);

    self.pw = self.parent().width();
    self.x = 0;

    self._width = 0;
    self.imagesLoaded = 0;
    self.imagesCount = self.find('img').length;
    self.find('img').each(function() {
      $(this).load(function() {
        self.imagesLoaded+=1;
        self._width += $(this).parent().parent().outerWidth();
        self.css({
          'width' : (self._width + 1) + 'px'
        });
        if (self.imagesLoaded == self.imagesCount) {
          
          setTimeout(function() {

            self.css({
              'width': (self.width() + 12) + 'px'
            });

            if (self._width > self.parent().width()) {
              self.parent().parent().find('.arrowLeft, .arrowRight').css({
                'visibility' : 'visible'
              });
              self.parent().parent().find('.arrowLeft').hover(
                function() {
                  self.speed = -10;
                  self.interval = setInterval(function() {
                    self.x -= self.speed;
                    if (self.x < -self._width + self.pw) {
                      self.x = -self._width + self.pw;
                    } else if (self.x > 0) {
                      self.x = 0;
                    }
                    self.css({
                      'margin-left' : self.x + 'px'
                    });
                  }, 40);
                },
                function() {
                  clearInterval(self.interval);
                }
              );
              self.parent().parent().find('.arrowRight').hover(
                function() {
                  self.speed = 10;
                  self.interval = setInterval(function() {
                    self.x -= self.speed;
                    if (self.x < -self._width + self.pw) {
                      self.x = -self._width + self.pw;
                    } else if (self.x > 0) {
                      self.x = 0;
                    }
                    self.css({
                      'margin-left' : self.x + 'px'
                    });
                  }, 40);
                },
                function() {
                  clearInterval(self.interval);
                }
              );
            } else {
              var t = Math.floor((self.parent().width() - self._width)/2); 
               self.css({
                   'margin-left': t + 'px'
              });
            }
          
          }, 200);
        }
      });
    });
    self.css({
      'width' : self._width + 'px'
    });
    self.find('img').hover(
      function () {
        if ($(this).parent().parent().hasClass('first')) {
          $(this).css({
            'margin-top' : '-9px',
            'width' : ($(this).width() + 18) + 'px',
            'height': ($(this).height() + 18) + 'px'
          });
          $(this).parent().parent().css({
            'padding' : '0 12px 0 0',
            'margin-left': '-9px',
            'margin-right': '-9px'
          });
          self.parent().css({
            'margin': '11px 35px 11px 25px',
            'padding': '10px 0 10px 10px'
          });
        } else if ($(this).parent().parent().hasClass('last')) {
          $(this).css({
            'margin-top' : '-9px',
            'width' : ($(this).width() + 18) + 'px',
            'height': ($(this).height() + 18) + 'px'
          });
          $(this).parent().parent().css({
            'padding' : '0 0 0 12px',
            'margin-left': '-9px',
            'margin-right': '-9px'
          });
          self.parent().css({
            'margin': '11px 25px 11px 35px',
            'padding': '10px 10px 10px 0'
          });
        } else {
          $(this).css({
            'margin-top' : '-9px',
            'width' : ($(this).width() + 18) + 'px',
            'height': ($(this).height() + 18) + 'px'
          });
          $(this).parent().parent().css({
            'padding' : '0 3px 0 3px'
          });
        }
      },
      function () {
        $(this).css({
          'margin-top' : '0',
          'width' : ($(this).width() - 18) + 'px',
          'height': ($(this).height() - 18) + 'px'
        });

        if ($(this).parent().parent().hasClass('first')) {
          $(this).parent().parent().css({
            'padding' : '0 12px 0 0',
            'margin-left': '0',
            'margin-right': '0'
          });
          self.parent().css({
            'margin': '11px 35px 11px 35px',
            'padding': '10px 0 10px 0'
          });
        } else if ($(this).parent().parent().hasClass('last')) {
          $(this).parent().parent().css({
            'padding' : '0 0 0 12px',
            'margin-left': '0',
            'margin-right': '0'
          });
          self.parent().css({
            'margin': '11px 35px 11px 35px',
            'padding': '10px 0 10px 0'
          });
        } else {
          $(this).parent().parent().css({
            'padding' : '0 12px 0 12px'
          });
        }
      }
    );
  });
}

try
{
$.fancybox.resizeImage = function(img) {
  var w = img.width, h = img.height, r, maxw = 640, maxh = 480;
  if (w > maxw || h > maxh) {
    if (w * 3 > h * 4) {
        r = h / w;
        w = maxw;
        h = w * r
    } else {
        r = w / h;
        h = maxh;
        w = h * r
    }
  }

  return { 'width': Math.round(w) + 'px', 'height': Math.round(h) + 'px'};
}
jQuery.fn.oferiaFancyBox = function() {

  return this.each(function() {

    var title = $(this).attr('title'),
      description = $(this).attr('description'),
      imgPreloader, undef;

    $(this).fancybox({

      'onStart' : function() {
//        $.fancybox.showActivity();
        $('#fancybox-inner').css('visibility', 'hidden');
      },
      'onComplete' : function(currentArray, currentIndex, currentOpts) {
        if (title == undef) {
          title = '';
        }
        if (description == undef) {
          description = '';
        }

        $.fancybox.showActivity();
        imgPreloader = new Image();

        imgPreloader.onerror = function() {
          fancybox_error();
        };

        imgPreloader.onload = function() {
          var b = $.fancybox.resizeImage(this), c, h, w, inner, wrap;

          imgPreloader.onerror = null;
          imgPreloader.onload = null;
          $('#fancybox-inner').html('<table class="fancybox-inner-content">' +
            (title != '' ? '<tr><td class="fancybox-inner-content-title" style="width: ' + b.width + '">' + title + '</td></tr>' : '') +
            (description != '' ? '<tr><td class="fancybox-inner-content-description" style="width: ' + b.width + '">' + description + '</td></tr>' : '') +
            '<tr><td class="fancybox-inner-content-image"><img id="fancybox_img" src="' + imgPreloader.src + '" style="width: ' + b.width + ';height: ' + b.height + '" /></td></tr>\n\
            <tr><td class="fancybox-inner-content-position">Obrazek ' + (currentIndex + 1) + ' z ' + currentArray.length + '</td></tr></table>');
          $.fancybox.hideActivity();

          inner = $('#fancybox-inner');
          wrap = $('#fancybox-wrap');

          c = inner.find('.fancybox-inner-content');
          h = c.outerHeight() + 20;
          w = c.outerWidth() + 20;

          wrap.css({
            'height': h + 'px',
            'width': w + 'px'
          });
          inner.css({
            'height':  h + 'px',
            'width':  w + 'px'
          });

          $.fancybox.center();
          $('#fancybox-inner').css('visibility', 'visible');
        };
        imgPreloader.src = $(this).attr('href');
      },
      'overlayColor' : '#000',
      'overlayOpacity' : 0.85,
      'titleShow' : false,
      'autoScale' : false,
      'width' : 640,
      'height': 480
    });
  });
};

}catch(e){}
