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));
		}
	});
	

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

	jQuery("#favourites").click(function() {
		arctBookmarkIt('KK Soške elektrarne', 'http://www.socakajak-klub.si');
	});

	/*--- printing ---*/

	jQuery(".print").click(function(e) {
		e.preventDefault();
		window.print();
	});
	
	

	/* --- main menu --- */
	
	function initMenuBorders() {
		$("li.menu-level1").each(function() {
			$(this).children('a.menu-level1').css("-moz-box-shadow","0px 1px 0px white");
			$(this).children('a.menu-level1').css("borderBottomColor","#cfcfcf");											
		});		
		
		$("li.menu-level1-open").each(function() {
			$(this).prev('li').find('a.menu-level1').css("-moz-box-shadow"," 0px 1px 0px transparent");
			$(this).prev('li').find('a.menu-level1').css("borderBottomColor","transparent");		
			$(this).children('a.menu-level1').css("-moz-box-shadow","0px 1px 0px transparent");
			$(this).children('a.menu-level1').css("borderBottomColor","transparent");											
		});	
	}
	
	$("#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").show();
			$(this).next("ul").show();
		}
	});
	

	$("#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").slideUp('fast'); // hide all of the siblings' uls
		liEl.find("ul ul").slideUp('fast'); // hide child uls
		liEl.find("ul:first").slideToggle('fast'); // toggle the current submenu
		
		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
		
		initMenuBorders();
		
		// prevent jumping to the top of the page for invalid (#) links
		if (liEl.find("a").attr("href") == '#') {
			e.preventDefault();
		}
	
	});
	
	initMenuBorders();
	
	$("#main-menu li.menu-level1").mouseover(function() {
		$(this).prev('li').find('a.menu-level1').css("-moz-box-shadow"," 0px 1px 0px transparent");
		$(this).prev('li').find('a.menu-level1').css("borderBottomColor","transparent");		
		$(this).children('a.menu-level1').css("-moz-box-shadow"," 0px 1px 0px transparent");
		$(this).children('a.menu-level1').css("borderBottomColor","transparent");											
	});	
	
	$("#main-menu li.menu-level1").mouseout(function() {
	
		$("li.menu-level1").each(function() {
			$(this).children('a.menu-level1').css("-moz-box-shadow","0px 1px 0px white");
			$(this).children('a.menu-level1').css("borderBottomColor","#cfcfcf");											
		});			
	
		$("li.menu-level1-open").each(function() {
			$(this).prev('li').find('a.menu-level1').css("-moz-box-shadow"," 0px 1px 0px transparent");
			$(this).prev('li').find('a.menu-level1').css("borderBottomColor","transparent");		
			$(this).children('a.menu-level1').css("-moz-box-shadow"," 0px 1px 0px transparent");
			$(this).children('a.menu-level1').css("borderBottomColor","transparent");											
		});
		
	});				

	
	/* --- 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();
		}
	});	


	/* --- 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
			}
		});
	}


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

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



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

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

	
	
	/* --- 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]);
				
				// check for thumbs which are too wide and remove the height attribute / add width
				if (jQuery(this).width() <= jQuery("img", this).width()) {
					jQuery("img", this).removeAttr("height");
					jQuery("img", this).width(jQuery(this).width());
				}
				
				cnt++;
			});
		}
	}
	
	function initImageDescription() {
		$('.image-left img').each(function() {
			newWidth = $(this).width()-14;
			$(this).parent('a').next('span').css('width',newWidth+'px');
		});
		$('.image-right img').each(function() {
			newWidth = $(this).width()-14;
			$(this).parent('a').next('span').css('width',newWidth+'px');
		});
		$('.image img').each(function() {
			newWidth = $(this).width()-14;
			$(this).parent('a').next('span').css('width',newWidth+'px');
		});		
	}
	

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

	$('input:text').textBoxHint(); // titles to input text
	$(".table-data").zebraStripeIt(); // alternate coloring of table rows
	
	//fix footer column height
	maxHeight = 0;
	if ($("#footer-col1").height() > $("#footer-col2").height()) {
		maxHeight = $("#footer-col1").height();
	}else {
		maxHeight = $("#footer-col2").height();
	}
	
	$("#footer-col1").css('height',maxHeight+'px');
	$("#footer-col2").css('height',maxHeight+'px');
	
	/* wait for images to load too */
	$(window).load(function() {
		initPhotogallery(); // initialize the photogallery
		initImageDescription(); //fix image description width 
	});


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

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

});
