jQuery(document).ready(function() {

	/*
	// jQuery Events Debugging
	$.fn.listHandlers = function(events, outputFunction) {
	    return this.each(function(i){
	        var elem = this,
	            dEvents = $(this).data('events');
	        if (!dEvents) {return;}
	        $.each(dEvents, function(name, handler){
	            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
	               $.each(handler, function(i,handler){
	                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
	               });
	           }
	        });
	    });
	};
	*/

	var urlDirFull = jQuery.url.attr("directory");

	/* --- jQuery extensions --- */
	
	// css properties selectors
	jQuery.extend(jQuery.expr[':'],{
		float: function(a) {
		  return (jQuery(a).css("float") === "left" || jQuery(a).css("float") === "right");
		},
		inline: function(a) {
		  return jQuery(a).css("display") === "inline";
		},
		marginx: function(a) {
		  return ((parseInt(jQuery(a).css("margin-left")) > 0) || (parseInt(jQuery(a).css("margin-right")) > 0));
		},
		marginy: function(a) {
		  return ((parseInt(jQuery(a).css("margin-bottom")) > 0) || (parseInt(jQuery(a).css("margin-top")) > 0));
		},
		margin: function(a) {
		  return ((parseInt(jQuery(a).css("margin-left")) > 0) || (parseInt(jQuery(a).css("margin-right")) > 0) || (parseInt(jQuery(a).css("margin-bottom")) > 0) || (parseInt(jQuery(a).css("margin-top")) > 0));
		}
	});
	
	/* --- jQuery extensions --- */
	

	/* --- bookmark & set as homepage --- */

	jQuery("#s-m-fav").click(function() {
		arctBookmarkIt('Naslov priljubka', 'http://www.spletna-stran.si');
	});
	jQuery("#set-as-homepage-button").click(function() {
		arctSetAsHomepage(this, 'http://www.spletna-stran.si');
	});

	/* --- END bookmark & set as homepage --- */


	/*--- printing ---*/

	jQuery("#s-m-print").click(function(e) {
		e.preventDefault();
		window.print();
	});

	/*--- END printing ---*/
	
	
	/*--- poll ---*/
	
	jQuery("form#poll-form").submit(function() {
		var responseData = '';
		if (jQuery('#multi-answers').val() != '1') 
			// one answer
			responseData = jQuery("form#poll-form input:checked").val();
		else {
			// multiple answers
			jQuery("form#poll-form input:checked").each(function () {
				responseData += this.value + ' ';
			});
		}
		jQuery.post("/util/ajaxresponse.php",{
				func: "poll", 
				response: responseData
		     }, function(html) {
		   showPoll(html);
		 });
		return false;
	});

	function showPoll(htmlResponse) {
		jQuery("#poll-container").html(htmlResponse);
		jQuery("#poll-container img").each(function() {
			var tmp = jQuery(this).attr("class");
			var aVals = tmp.match(/[0-9]+$/); // get number at the end of the string
			var val = aVals[0];
			jQuery(this).animate({ width: val+"px" }, 1000 );
		});
	}
	
	/*--- END poll ---*/
	
	
	/*--- FAQ ---*/
	
	if ($("div#faq-form-section").length) {
		$("p#faq-form-toggle").slideDown();
		$("p#faq-form-toggle").click(function() {
			$("p#faq-form-toggle").slideUp(500);
			$("div#faq-form-section").slideToggle(500);
		});
	}
	
	if ($("div#faq-list").length) {
		$("div#faq-list h2").click(function() {
			$(this).next("dl.faq-list").slideToggle(500);
			$(this).next("dl.faq-list").toggleClass('open');
			$(this).toggleClass('open');
		});
	}
	
	/*--- END FAQ ---*/
	

	/* --- main menu --- */

	$("#main-menu a[href != '#']").each(function() {
		// consider the id in the url when comparing
		if($(this).attr("class") == "m-m-useid"){
			// find matching url
			var urlDir = urlDirFull;
			var aHref = $(this).attr("href"); // trim IDs from url (example. "123758363528/")
		// ignore the id in the url when comparing
		} else {
			// find matching url
			var urlDir = urlDirFull.replace(/all\/|[_\d]+\/.*/g, ''); // trim IDs from url (.../all/34235435234623/313/123123/...)
			var aHref = $(this).attr("href").replace(/all\/|[_\d]+\/.*/g, ''); // trim IDs from url (.../all/34235435234623/313/123123/...)
		}
		
		// the page url is the same as the menu link, so open the menu
		if (urlDir == aHref) {
			$(this).parents("li").each(function() {
				var tmp = $(this).attr('class');
				var aLevels = tmp.match(/[0-9]+/); // get number at the end of the string
				//if (aLevels != undefined) {
				var level = aLevels[aLevels.length-1];				
				$(this).addClass("menu-level"+level+"-open");
				//}
			});
			$(this).parents("ul").css('display', 'inline');
			$(this).next("ul").css('display', 'inline');
		}
	});

	$("#main-menu span").click(function(e) {
		var liEl = $(this).parents("li:first"); // li element
		var liSibl = liEl.siblings(); // sibling li elements
		
		// find out li level
	   	var tmp = liEl.attr('class');
	   	var aLevels = tmp.match(/[0-9]+/);
	   	var tgtlevel = aLevels[aLevels.length-1]; // tgt level
		
		liSibl.find("ul").hide(); // hide all of the siblings' uls
		liEl.find("ul ul").hide(); // hide child uls
		toggleEl = liEl.find("ul:first");
		if (toggleEl.css('display') == 'inline') {
			toggleEl.css('display', 'none');
		} else {
			toggleEl.css('display', 'inline');
		}
		
		liSibl.removeClass("menu-level"+tgtlevel+"-open"); // remove the 'm-m-levelX-open' class from all the siblings of the clicked li
		liSibl.find('li').each(function() {
			var tmp = jQuery(this).attr('class');
			var aLevels = tmp.match(/[0-9]+/); // get number at the end of the string
			var level = aLevels[aLevels.length-1];
			jQuery(this).removeClass("menu-level"+level+"-open"); // remove the 'm-m-levelX-open' class from all the children of the siblings of the clicked li
		});
		liEl.find('li').each(function() {
			var tmp = jQuery(this).attr('class');
			var aLevels = tmp.match(/[0-9]+/); // get number at the end of the string
			var level = aLevels[aLevels.length-1];
			jQuery(this).removeClass("menu-level"+level+"-open"); // remove the 'm-m-levelX-open' class from all the children of the clicked li
		});
		
		liEl.toggleClass("menu-level"+tgtlevel+"-open"); // toggle class 'm-m-levelX-open' of the clicked li
		
		// prevent jumping to the top of the page for invalid (#) links
		if (liEl.find("a").attr("href") == '#') {
			e.preventDefault();
		}
	});

	/* --- END main menu --- */


	/* --- text resizing --- */

	jQuery("#t-s-normal").click(function(e) {
		jQuery("body").css({"fontSize": "62.5%"});
		jQuery.cookie('page_font_size', "62.5%", {path: '/'}); // save font size in cookie
	})

	jQuery("#t-s-larger").click(function(e) {
		jQuery("body").css({"fontSize": "70%"});
		jQuery.cookie('page_font_size', "70%", {path: '/'}); // save font size in cookie
	})

	jQuery("#t-s-largest").click(function(e) {
		jQuery("body").css({"fontSize": "85%"});
		jQuery.cookie('page_font_size', "85%", {path: '/'}); // save font size in cookie
	})

	// retrieve font size if cookie has been set
	var cookieFontSize = jQuery.cookie('page_font_size');
	if (cookieFontSize != '') {
		jQuery("body").css({"fontSize": cookieFontSize});
	}

	/* --- END text resizing --- */


	/* --- alt style switcher --- */
	
	function switchStylestyle(styleName) {
		$('link[@rel*=style][title]').each(function(i) {
        	this.disabled = true;
	        if (this.getAttribute('title') == styleName) this.disabled = false;
	    });
		$.cookie('style', styleName, {path: '/'});
	}
	
	function clearStylestyle() {
		$('link[@rel*=style][title]').each(function(i) {
        	this.disabled = true;
	    });
		$.cookie('style', null, {path: '/'});
	}
	
	$('#s-m-s-contrast').click(function() {
		var c = $.cookie('style');
		if (c) {
			clearStylestyle();
		} else {
    		switchStylestyle("high contrast style");
		}
    	return false;
	});
	var c = $.cookie('style');
	if (c) switchStylestyle(c);

	/* --- END alt style switcher --- */
	
	
	/* --- anchor click scrolling --- */
	
	$('a[href^=#]').click(function(e) {
		// scroll to anchor if there is actually more after the # sign in the link
		if ($(this).attr('href').length > 1) {
			scrollToElementName = $(this).attr('href').substr($(this).attr('href').indexOf("#")+1);
			scrollTo = $("a[name="+scrollToElementName+"]").offset().top;
			$('html, body').animate({scrollTop: scrollTo}, 500);
			e.preventDefault();
		}
	});
	
	/* --- END anchor click scrolling --- */	


	/* --- populate text fields and clear them on focus --- */

	jQuery.fn.textBoxHint = function () {
		return this.each(function () {
	    	var t = jQuery(this); // get jQuery version of 'this'
			var title = t.attr('title'); // get it once since it won't change
		    // only apply logic if the element has the attribute
		    if (title) {
				// on blur, set value to title attr if text is blank
				t.blur(function () {
					if (t.val() == '') {
						t.val(title);
						t.addClass('blur');
					}
				});
				// on focus, set value to blank if current value
				// matches title attr
				t.focus(function () {
					if (t.val() == title) {
						t.val('');
						t.removeClass('blur');
					}
				});
				// clear the pre-defined text when form is submitted
				t.parents('form:first()').submit(function() {
					if (t.val() == title) {
						t.val('');
						t.removeClass('blur');
					}
				});
				t.blur(); // now change all inputs to title
			}
		});
	}

	/* --- END populate text fields and clear them on focus --- */


	/* --- table zebra striping --- */

	jQuery.fn.zebraStripeIt = function() {
		jQuery("tr:odd", this).addClass("odd"); // set class to every odd row in a table
	}

	/* --- END table zebra striping --- */


	/* --- image framer --- */

	$.fn.initImageFramer = function() {
		$(this).each(function() {
			var imageTitle = $(this).attr("title"); // get title text

			if (imageTitle == '') {
				imageTitle = $(this).attr("alt"); // no title text available, use alt text
			}
			// no text available - skip
			if (imageTitle != '') {
				$(this).wrap('<div id="photo-frame"></div>');
				//$(this).after('<p>'+imageTitle+'</p>');
			}
		});
	}

	/* --- END image framer --- */


	/* --- external links --- */

	$.fn.markExternalLinks = function() {
		$(this).filter(function() {
			return this.hostname && this.hostname !== location.hostname;
		}).addClass("external");
	}

	/* --- END external links --- */


	/* --- calendar --- */

	function initCalendar() {
		// advance a month
		jQuery("#cal-next-month").click(function(e) {
			var cName = jQuery("#cal-next-month").attr("class");
			var y = cName.substr(6,4);
			var m = cName.substr(10,2);
			jQuery("#calendar-response").load("/util/ajaxresponse.php", { 'func': 'outputCalendar', 'y': y, 'm': m, 'eventsStrId':'28_slo' }, function() {
				initCalendar();
			});
			e.preventDefault();
		});

		// backtrack a month
		jQuery("#cal-prev-month").click(function(e) {
			var cName = jQuery("#cal-prev-month").attr("class");
			var y = cName.substr(6,4);
			var m = cName.substr(10,2);
			jQuery("#calendar-response").load("/util/ajaxresponse.php", { 'func': 'outputCalendar', 'y': y, 'm': m, 'eventsStrId':'28_slo'}, function() {
				initCalendar();
			});
			e.preventDefault();
		});
	}
	
	/* --- END calendar --- */
	
	
	/* --- Photogallery --- */

	function initPhotogallery() {
		if (jQuery("#photo-gallery-container").length) {
			var galleryWidth = jQuery("div#photo-gallery-container").width();
			var galleryItemWidth = jQuery("div#photo-gallery-container .photo-gallery-item:first").width();
			var itemsPerRow = Math.floor(galleryWidth / galleryItemWidth);
			var cnt = 1;
			var cntItems = 0;
			var maxHeight = 0;
			var aHighest = new Array();
			var nItems = jQuery("div#photo-gallery-container .photo-gallery-item").length;
			jQuery("div#photo-gallery-container .photo-gallery-item").each(function() {
				cntItems++;
				if (cnt > itemsPerRow) {
					cnt = 0;
					maxHeight = 0;
				}
				//var totalHeight = 
				if (jQuery(this).height() > maxHeight) {
					maxHeight = jQuery(this).height();
				}
				if (cnt == itemsPerRow || cntItems == nItems) {
					aHighest.push(maxHeight);
				}
				cnt++;
			});
			cnt = 1;
			cnt2 = 0;
			jQuery("div#photo-gallery-container .photo-gallery-item").each(function() {
				if (cnt > itemsPerRow) {
					cnt = 1;
					cnt2++;
				}
				jQuery(this).height(aHighest[cnt2]);
				cnt++;
			});
		}
	}
	
	/* --- END Photogallery --- */
	
	
	/* --- Animated gallery --- */

	$.fn.animateGallery = function() {
		var animGallery = jQuery(this);
		var moves = 0; // how many times the pics moved
		var nPics = $("ul.gallery li", animGallery).length; // num of pics
		var prevMove = nPics - 1; // previous move number
		var nTransitions = 0;
		var interval;
		var animPause = 5000;
		var transitionSpeed = 500;
		$("ul.gallery ", animGallery).css("width", 300*nPics+'px'); // set gallery strip width
		
		
		appendString = '<ul id="featured-news-counters">';		
		for (i=0; i<nPics; i++) {
			j = i + 1;
			appendString += '<li class="counter counter'+i+'">'+j+'</li>';
		}
		appendString += '</ul>';
		$(this).append(appendString);
		$("#featured-news-counters .counter0").addClass("counter0-on");
		
		function animateGallery(event) {
			nTransitions++;
			if (moves == nPics - 1) {
				moves = 0;
				prevMove = nPics - 1;
				$("ul.gallery", animGallery).animate({ marginLeft: "0px" }, transitionSpeed);
				$("#featured-news-counters .counter"+(nPics - 1)).removeClass("counter"+(nPics - 1)+"-on");
				$("#featured-news-counters .counter0").addClass("counter0-on");
			} else {
				prevMove = moves;
				moves++;
				$("#featured-news-counters .counter"+prevMove).removeClass("counter"+prevMove+"-on");
				$("#featured-news-counters .counter"+moves).addClass("counter"+moves+"-on");
				$("ul.gallery", animGallery).animate({ marginLeft: "-=300px" }, transitionSpeed);
			}
		}
		
		if (nPics > 1) {
			interval = setInterval(animateGallery, animPause);
		}

		$(this).hover(
			function () {
				clearInterval(interval); // stop animation on hover
			}, 
			function () {
				interval = setInterval(animateGallery, animPause); // resume animation
			}
		);
		
		$('#featured-news-counters .counter').click(function() {
			var counterN = $(this).text() - 1;
			moves = counterN;
			var counterPrevN = 0;
			$("ul.gallery", animGallery).animate({ marginLeft: "-"+counterN*300+"px" }, transitionSpeed);
			if (counterN == 0) {
				counterPrevN = nPics - 1;
			} else {
				counterPrevN = counterN - 1;
			}
			$("#featured-news-counters .counter"+counterPrevN).removeClass("counter"+counterPrevN+"-on");
			$("#featured-news-counters .counter"+counterN).addClass("counter"+counterN+"-on");
		});
	}	
	
	/* --- END Animated gallery --- */
	
	
	/* --- make all given objects the same height --- */
	
	$.fn.equalHeightColumns = function() {
		var tallest = 0;
		
		$(this).each(function() {
			if ($(this).outerHeight(true) > tallest) {
				tallest = $(this).outerHeight(true);
			}
		});
		
		$(this).each(function() {
			var diff = 0;
			diff = tallest - $(this).outerHeight(true);
			$(this).height($(this).height() + diff);
		});
	};	
	
	
	/* --- Animated header images --- */
	
	function animateHeaderImages() {
		
	}
	
	/* --- END Animated header images --- */


	/* --- Cart ajax --- */
	
	$(".btnCart").click(function() {
		var idValue = $(this).attr("id");
		var id = idValue.substring(4);
		var quantity = $(this).parent(".shop-item").find("dd.form").find(".form-line-holder-1").find("input[name=quantity]").val();
		var price = $(this).prevAll("input[name=price]").val();
		var pName = $(this).parent(".shop-item").find("dd.form").find(".form-line-holder-2").find("input[name=pName]").val();
		var size = $(this).parent(".shop-item").find("dd.form").find(".form-line-holder-3").find("input[name=shirtSize]:checked").val();
		//alert(size);
		var data = {
			'articleId': id,
			'quantity': quantity,
			'price': price,
			'size': size,
			'name': pName
		}
		jQuery($("#cart-container")).load("/util/ajaxresponse.php?func=addCart", data);
	});
	
	
	
	function cartUpdate(){
		
	}
	
	function cartUpdateAll(){
		$(".imgCartEdit").click(function(e) {
			
			var idValue = $(this).attr("id");
			var id = idValue.substring(4);
			var data = {
				'articleId': id
			}
			jQuery($("#text-content-container")).load("/util/ajaxresponse.php?func=removeCart", data, function() {
				cartUpdateAll();
			});
			
		});
		
		$("#refresh-cart").click(function(e) {
			var aValues = new Array();
			var i = 0;
			$("input.quantity").each(function(e) {
				var idValue = $(this).attr("id");
				var id = idValue.substring(4);
				aValues[i] = id+"-"+$(this).val();
				i++;
			});
			var data = {
				'aValues[]' : aValues
			}
			jQuery($("#text-content-container")).load("/util/ajaxresponse.php?func=updateCart", data, function() {
				cartUpdateAll();
			});
		});
	}
	

	cartUpdateAll();
	
	/* --- END Cart ajax --- */

	$("#f6_1, #f6_4").click(function() {
		$(".group-pet, .group-druzinska").hide();
	});

	$("#f6_2").click(function() {
		$(".group-pet").hide();
		$(".group-druzinska").show();
	});
	
	$("#f6_3").click(function() {
		$(".group-druzinska").hide();
		$(".group-pet").show();
	});

	/* --- on load --- */

	if ($("#f6_2:checked").val() == '2') {
		$(".group-druzinska").show();
	}
	
	if ($("#f6_3:checked").val() == '3') {
		$(".group-pet").show();
	}

	jQuery('input:text').textBoxHint(); // titles to input text
	jQuery(".table-data").zebraStripeIt(); // alternate coloring of table rows
	jQuery("#text-content-container img.content-photo").initImageFramer(); // format content images with title
	jQuery("#text-content-container a, ul.grouped-link-list a").markExternalLinks(); // adds class to external links
	initCalendar(); // initialize the calendar
	animateHeaderImages();
	$("#featured-news").animateGallery();
	$("#header").smoothDivScroll({
		scrollWrapper: "#head-photo-scroller",
		scrollableArea: "#head-photo-container",
		autoScroll: "always", 
		autoScrollDirection: "endlessloop", 
		autoScrollSpeed: 1
	});
	
	/* wait for images to load too */
	jQuery(window).load(function() {
		initPhotogallery(); // initialize the photogallery
		$("#text-content-container dl.shop-item").equalHeightColumns();
	});
	
	/* --- END on load --- */


	/* --- window resizing --- */
	
	jQuery(window).resize(function() {
		// resize elements, reposition elements, ...
	});
	
	/* --- END window resizing --- */

	// List all handlers for all events of all elements:
	//$('*').listHandlers('*', console.info);

});
