/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */
	
	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "Zbývá znaků: %1",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;
		
		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};
		
		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};
		
		return this.each(function () {
			var container = (!settings.container.match(/^<.+>$/)) 
				? $(settings.container) 
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			$(this)
				.bind("keydown", function () { count(this, container); })
				.bind("keypress", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("focus", function () { count(this, container); })
				.bind("mouseover", function () { count(this, container); })
				.bind("mouseout", function () { count(this, container); })
				.bind("paste", function () { 
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};

})(jQuery);

$(document).ready(function(){
	
	corners();
	pgCar();
	pgCars();
	gUsers();
	lightboxes();
	leasing();
	
/* 	if($("#page.print").length > 0) {
		if(confirm("Přejete si vytisknout tuto stránku?")) {
			window.print();
		}
	} */
	
	$("#Ff_br").each(function() {
		$(this).change(function(){
			$("#Ff_mo").load("/ajax.php?cmd=modelsublist_" + $(this).val() + " option", false, function(){
				$(this).prepend('<option value="" selected="selected">nerozhoduje</option>');
			});
			
		});
	});
	
	
	adv = $(".srcAdvanced").length > 0 ? true : false;
	
	if(!adv) {
		$("#advanced").hide();
		$("#advanced input[name=a]").attr("value", "0");
	}
	
	$("#frmSearch .fBlock").append('<span class="arBotGry"><a id="advLink" href="javascript:void(0)" title="podrobné hledání / jednoduché hledání"></a></span>').each(function(){
		$(this).find("#advLink").each(function(){
			
			$(this).text($(this).attr("title").split(" / ")[(adv ? 1 : 0)]);                                     
			
			}).click(function(){
			
				if(!adv) {
					$("#advanced").show();
					/*$("#article").animate({marginTop: "135px"}, 1000, function(){});*/
					$("#page").addClass("srcAdvanced");
					$("#advanced input[name=a]").attr("value", "1");
					adv = true;
					$(this).text($(this).attr("title").split(" / ")[1]).parent().addClass("emph");
					
				} else {
					$("#page").removeClass("srcAdvanced");
					$("#advanced").hide();
					/*$$("#article").animate({marginTop: "0px"}, 1000);*/
					$("#advanced input[name=a]").attr("value", "0");
					adv = false;
					$(this).text($(this).attr("title").split(" / ")[0]).parent().removeClass("emph");
				}
		});
	});
	
	$("#frmSearch").submit(function(){
		if($(this).find("input[name=a]").val() == 0){
			$("#advanced").remove();
		}
	});
	
});

this.lightboxes = function() {
	
	if($("#page.print").length > 0) {return false;}
	
	str = '';
	$('a[rel^=lightbox]').each(function(){
		uq = $(this).attr("rel").substr(9);
		if(str.indexOf("<" + uq + ">") == -1) {
			str += "<" + uq + ">";
		}
	});
	
	gals = str.substr(1, str.length-2).split("><");
	for(i = 0; i < gals.length; i++) {
		$("a[rel=lightbox-" + gals[i] + "]").lightBox({
			containerResizeSpeed: 400,
			txtImage: "Obrázek / Image :",
			txtOf: "/",
			imageLoading: "/img/lb-loading.gif",
			imageBtnClose: "/img/lb-btn-close.gif",
			imageBtnPrev: "/img/lb-btn-prev.gif",
			imageBtnNext: "/img/lb-btn-next.gif"
		});
	}

}

this.corners = function() {
	
	if($("#page.print").length > 0) {return false;}
	
	ratio = "10px";
	
	$(".rounded").corner();
	$(".roundedTop").corner("tl tr " + ratio);
	$(".roundedTopLeft").corner("tl" + ratio);
	$(".roundedTopRight").corner("tr" + ratio);
	$(".roundedBot").corner("bl br" + ratio);
	$(".roundedBotLeft").corner("bl" + ratio);
	$(".roundedBotRight").corner("br" + ratio);
	
	$("#nav .nav1, #nav .nav1 a").corner("tl" + ratio + " cc:#000");
	$("#nav li:last a").corner("tr" + ratio + " cc:#000");
	$("#search").corner("top " + ratio + " cc:#7C7C7C"); //corner("bl cc:#E1E8F0");
	//$(".pgIndex #main").corner("tl " + ratio + " cc:#8D8D8D");
	$("#ixMoreCars").corner("bl br " + ratio + " cc:#E5E5E5");
	$(".txtBlock h2").corner("tl tr 7px cc:#E5E5E5");
	$(".counter").corner("tl tr " + ratio + " cc:#EFF2F7");
	
	$(".alert").corner("bl br " + ratio + " cc:#EFF2F7").corner("top " + ratio + " cc:#E1E8F0");
	
}


this.pgCar = function(){
	
	if($("#page.print").length > 0) {return false;}
	
	if($(".galImgs").length > 0) {
		
		emph = 0;
		ims = Array();
		pth = Array();
		
		$(".galItem").each(function(){
			ix = parseInt(this.id.substr(2)) - 1;
			ims[ix] = this.id;
			if($(this).hasClass("emph")) {
				emph = ix;
			}
		}).hover(function(){
			//alert(this.childNodes[0].src);
			$(".galImgs .emph").removeClass("emph");
			$("#galMainImg img").attr("src", this.childNodes[0].childNodes[0].src);
			$("#galMainImg").attr("href", this.href);
			$(this).toggleClass("emph");
		},function(){
		
		});
		
		all = ims.length;
		start = parseInt(emph / 4) * 4;
		$(".galNoItem").hide();
		
		if(all > 4) {
			
			for(i = 0; i < all; i++) {
				if(i < start || i >= start + 4) { $("#" + ims[i]).hide(); }
			}
			
			$(".galImgs").each(function(){
				
				$(this).append('<span class="galStepper"><a href="javascript:void(0)" class="next" title="Další"><span class="hidden">&gt;</span></a><a href="javascript:void(0)" class="prev" title="Předchozí"><span class="hidden">&lt;</span></a></span>');
				
				if(start + 4 > all - 1) {
					$(this).find(".next").addClass("disabled").removeAttr("href");
					$(".galNoItem").show();
				}
				
				if(emph == 0) {
					$(this).find(".prev").addClass("disabled").removeAttr("href");
				}
				
				
				$(this).find(".next").click(function(){
					if(start + 4 <= all - 1) {
						start = start + 4;
						for(i = 0; i < all; i++) {
							if(i < start || i >= start + 4) { $("#" + ims[i]).hide(); } else {$("#" + ims[i]).show();}
						}
						if(start + 4 > all - 1) {
							$(this).addClass("disabled").removeAttr("href");
							$(".galNoItem").show();
						}
						if(start > 0) {
							$(this).parents(".galImgs").find(".prev").removeClass("disabled").attr("href","javascript:void(0)")
						}
					}
				});
				
				$(this).find(".prev").click(function(){
					if(start - 4 >= 0) {
						$(".galNoItem").hide();
						start = start - 4;
						for(i = 0; i < all; i++) {
							if(i < start || i >= start + 4) { $("#" + ims[i]).hide(); } else {$("#" + ims[i]).show();}
						}
						if(start == 0) {
							$(this).addClass("disabled").removeAttr("href");
						}
						if(start + 4 <= all - 1) {
							$(this).parents(".galImgs").find(".next").removeClass("disabled").attr("href","javascript:void(0)")
							
						}
					}
				});
				
				
			});
		
		}
		
	}
	
}

this.gUsers = function() {
	
	if($("#page.print").length > 0) {return false;}
	
	$("#Ff_brand").each(function() {
		
		$(this).change(function(){
			$("#Ff_model").load("/ajax.php?cmd=modelsublist_" + $(this).val() + " option", false, function(){
				$(this).prepend('<option value="" selected="selected">Nerozhoduje</option>');
			});
		});
		
		
	});
	
	$("#massSelect").each(function() {
		tts = $(this).attr("title").split(" / ");
		$(this).click(function() {
			todo = $(this).text() == tts[0] ? 1 : 0;
			$(this).text(tts[todo]);
			if(todo == 1) {
				$(this).parents("table").find("input[type=checkbox]").attr('checked','');
			} else {
				$(this).parents("table").find("input[type=checkbox]").attr('checked','checked');
			}
		});
	});
	
	$("#Ff_description").charCounter(255);
	
/* 	$("#Ff_description").each(function(){
		ln = 255;
		$(this).parent().append('<span>Zbývá znaků: <span id="txtTodo">255</span></span>');
		txt2do = $(this).parent().find("#txtTodo");
		
		if($(this).val().length > ln) {
			$(this).val($(this).val().substr(0, ln));
		}
		txt2do.text(ln - $(this).val().length);
		
		$(this).keyup(function(){
			if($(this).val().length > ln) {
				alert("fuck");
				$(this).val($(this).val().substr(0, ln));
			}
			txt2do.text(ln - $(this).val().length);
			return false;
		});
		
		$(this).mouseup(function() {
			alert("f");
		});

	}); */
	
	// thumb view in image list
	$(".imDetail").hover(		
		function(){
			if($(".imDetailShow").length >= 1) {
				$(".imDetailShow").remove();
			}
			pth = $(this).children("img").attr("src");
			$(this).append('<img src="' + pth + '" class="imDetailShow" />');
		},
		function(){
			$(".imDetailShow").hide();
		}
	);
}

this.pgCars = function() {
	
	if($("#page.print").length > 0) {return false;}
	
 	$(".btnLi").hover(function(){
		$(this).children("ul").fadeIn();
	}, function(){
		$(this).children("ul").fadeOut();
	});
}

// leasingova kalkulacka
this.leasing = function() {
	
	$("#frmLeasing").submit(function(){

		p = $(this).find("#Ff_price").val();
		c = p.substr(p.indexOf(",-"));
		p = p.replace(/ /g,"").replace("&nbsp;","");
		p = p.substr(0, p.indexOf(",-"));
		
		du = $(this).find("#Ff_depositunit").val();
		dr = parseInt($(this).find("#Ff_depositrate").val());
		
		if(isNaN(dr)) {
			
			dr = "zadejte zálohu";
			
		} else {
			
			if(du == "%") {
				dr = dr / 100;
				dr = dr <= 1 ? dr : 1;
				d = Math.round(p * dr);
				dr = dr * 100;
				df = d + "" + c;
			
			} else {
				
				df = Math.round((dr / p) * 100) + " %";
				d = dr;
			}
			
			$(this).find("#Ff_deposit").text(df);
			
		}
		
		$(this).find("#Ff_depositrate").val(dr);
		
		t = parseInt($(this).find("#Ff_period").val())
		
		if(isNaN(t)) {
			t = "zadejte měsíce";
		} else {
			r = parseInt($(this).find("#Ff_period").val()) / 100;
			m = Math.round(((p - d) / t) * (1 + r));
			$(this).find("#Ff_monthly").text(m + "" + c);
		}
		
		$(this).find("#Ff_period").val(t);
		
		return false;
	});
	
	$("#Ff_period").focus(function(){$(this).val("");});
	$("#Ff_depositrate").focus(function(){$(this).val("");});
	
	
	return false;
}
