// jquery menu 
var arrowimages={down:['downarrowclass', '/img/arrows/arrow-down.png', 10], right:['rightarrowclass', '/img/arrows/arrow-right.png']}
var jquerycssmenu={

fadesettings: {overduration: 350, outduration: 100}, //duration of fade in/ out animation, in milliseconds

buildmenu:function(menuid, arrowsvar){
	jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
      $curobj.children("a").children().append(
				'<img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
				+'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
				+ '" style="border:0;" />'
			)
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					this._offsets={left:$(this).offset().left, top:$(this).offset().top}
					var menuleft=this.istopheader? 0 : this._dimensions.w
					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
					$targetul.css({left:menuleft+"px"}).fadeIn(jquerycssmenu.fadesettings.overduration)
					$(this).children("a").attr("class", "selected")
				},
				function(e){
					$(this).children("ul:eq(0)").fadeOut(jquerycssmenu.fadesettings.outduration)
					$(this).children("a").attr("class", "")
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
	}) //end document.ready
}
}
jquerycssmenu.buildmenu("menu", arrowimages)

// textlimit function

jQuery.fn.textlimit=function(counter_el, thelimit, speed) {
	var charDelSpeed = speed || 15;
	var toggleCharDel = speed != -1;
	var toggleTrim = true;
	
	var that = this[0];
	updateCounter();
	
	function updateCounter(){
		jQuery(counter_el).text(thelimit - that.value.length);
	};
	
	this.keypress (function(e){ if( this.value.length >= thelimit && e.charCode != '0' ) e.preventDefault() })
	.keyup (function(e){
		updateCounter();
		if( this.value.length >= thelimit && toggleTrim ){
			if(toggleCharDel){
				// first, trim the text a bit so the char trimming won't take forever
				that.value = that.value.substr(0,thelimit+100);
				var init = setInterval
					( 
						function(){ 
							if( that.value.length <= thelimit){ init = clearInterval(init); updateCounter() }
							else{ that.value = that.value.substring(0,that.value.length-1); jQuery(counter_el).text('trimming...  '+(thelimit - that.value.length)); };
						} ,charDelSpeed 
					);
			}
			else this.value = that.value.substr(0,thelimit);
		}
	});
	
};

$(document).ready(function(){

  var anchor = new String(window.location);
  if(anchor.indexOf('#')) {
		var $target = $(window.location.hash), target = window.location.hash;
		if (target) {
			var targetOffset = $target.offset().top;
			$('html').animate({scrollTop: targetOffset}, 400, function() {
				location.hash = target;
			});
		}
	}



	$('a[href*=#]').each(function() {
		if ( location.hostname == this.hostname || !this.hostname && this.hash.replace(/#/,'') ) {
			var $target = $(this.hash), target = this.hash;
			if (target) {
				var targetOffset = $target.offset().top;
				$(this).click(function(event) {
					event.preventDefault();
					$('html').animate({scrollTop: targetOffset}, 400, function() {
						location.hash = target;
					});
				});
			}
		}
	}); 

  $("#search input[name='dotaz']")
  .focus(function() {
    if($(this).val() == 'hledej...') $(this).val('');
  })
  .blur(function() {
    if($(this).val() == '') $(this).val('hledej...');
  });

	/* dialog error */				 
	$(".dialog.error").dialog({
		bgiframe: true,
		minHeight: 20,
		width: 200,
		height: 80,
		modal: true,
		show: 'slide',
		resizable: false,
		hide: 'slide'
	});
	
	$("#msg").dialog({
		bigframe: true,
		minwidth: 100,
		minHeight: 100,
		show: 'drop',
		hide: 'drop',
		resizable: false,
		position: ['right', 'bottom'], 
		open: function() { window.setTimeout('$("#msg").dialog("close")', 5000) }
	});
	
	$(".gb").mouseover(function(){
		$(".options", this).addClass("showed");
			$(".options").mouseover(function(){
				$(this).addClass("auto");
			}).mouseout(function(){
				$(this).removeClass("auto");
			});
	}).mouseout(function(){
		$(".options", this).removeClass("showed");
	});
		
	$(".permalink").bind("click", function(){
      $(this).next().dialog({
			bigframe: true,
			minwidth: 100,
			minHeight: 100,
			modal: true,
			title: "Stálý odkaz na příspěvek",
			show: 'drop',
			hide: 'drop',
			resizable: false,
			position: ['center', 'center']
		});
  });
	
	//$("textarea").textlimit('span.counter',256);
	
	/* input tip messages */
	$(".help").oxtip({float: "left", width: 200, opacity: 0.9, a: "mouseover", d: "mouseout"});
	$(".tip").oxtip({float: "right", maxWidth: 270, a: "focus", d: "blur"});
	
	/* cart */
	$("form.cart").bind("submit", function(){
	
    var selectedEffect = 'transfer';
    var options = { to: ".top-cart", className: 'ui-effects-transfer' };
		$(this).effect(selectedEffect,options,1000,callback);
		
		//callback function to bring a hidden box back
		function callback(){
			setTimeout(function(){
				$("#head:hidden").removeAttr('style').hide().fadeIn();
			}, 1000);
		};
		
		if(this.quantity.value == 0) {
      $("#productCart-"+this.productID.value).remove();
    }
	
	  $.post("/app/helper.php?action=topCart", 
          { productID: this.productID.value, quantity: this.quantity.value, stop: true },
          function(data){
            $("#head .top-cart").html(data);
          }); 
        
    if($(".product").length == 0) {
      //$("#cart").load("/app/helper.php?action=cart");
    } else {
      $("#productCart-"+this.productID.value).load("/app/helper.php?action=cartItem&pID="+this.productID.value);
    }
    
    return false;   
	});
	
	$("#bothOfPost:checked") ? $("#deliveryAddress").hide() : $("#deliveryAddress").show();
	$("#bothOfPost").click(function() {
    if($(this).is(":checked")) $("#deliveryAddress").hide("slow"); else { $("#deliveryAddress").show("slow"); }
  });
	
});

/* oxtip */
jQuery.fn.oxtip = function(e) {

	this.bind(e.a, function(){
		
		var de = document.documentElement;
		var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		var clickElementy = getAbsoluteTop(this.id); //set y position
		var clickElementx = getAbsoluteLeft(this.id); //set x position
		
		if(e.float == "left") clickElementx -= ((this.offsetWidth*1) + e.width); else clickElementx += ((this.offsetWidth*1) + 15);
		
		var div = "<div id='tip'><div class='arrow-"+e.float+"'></div>";
		if(this.title != false) div += "<div class='title'>"+this.title+"</div>";
		div += "<div id='tipText'><img src=\"/img/animations/tip-loader.gif\" alt=\"nahrávám...\" /></div></div>";
		
		$("body").append(div);//left side
		
		$('#tipText').load("/app/scripts/tip.php?tip="+this.name);
		$('#tip').css({left: clickElementx+"px", top: clickElementy+"px"});
		$('#tip').css({left: clickElementx+"px", top: clickElementy+"px", "width": e.width+"px", "max-width": e.maxWidth+"px", "-moz-opacity": e.opacity, "filter": "filter: alpha(opacity="+(e.opacity*100)+")"});
		$('#tip').show(500);
		
	});
	this.bind(e.d,function(){
		$('#tip').remove();
	})
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

jQuery.fn.stripTags = function() {
  return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};