/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 3/9/2009
 * @author Ariel Flesler
 * @version 1.4.1
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

// get URL parameters
$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}

// DOM ready
$(function(){

	// prevent H1 link
	$("h1 > a").click(function(e){e.preventDefault();});

	// remove menu border under ie7
	$("#mainmenu a:last").css("border-right",0);

	// submit buttons
	$("form a.submit").click(function(e){
		e.preventDefault();
		$(this).closest("form").submit();
		return false;
	});

	//rendelés form submit button
	$('form input.button').each(function(){
	   $(this).hide().after('<a class="submit button"><span>Rendelés elküldése</span></a>').next('a.button').click(function(){
            $(this).prev('input.button').click();
            });
	});

	// checkboxes
	$("form :checkbox").click(function(e){
		$("form #mailinglist").val(+$(this).is(":checked"));
	});
	
	// add alternate row class
	$('#main > article table').each(function(){ $("tr:even",this).addClass('alt'); } );
	
	// price table roll over rows
	$('#pricetable tr').mouseover(function() {
		$(this).addClass('highlight');
	}).mouseout(function(){
		$(this).removeClass('highlight');
	});
			
	// equal height for categories
	$("section.categories article.category:nth-child(3n-2)").each(function(index,element){
        var $this = $(this);
        var $next = $this.nextAll(".category:lt(2)");
		var maxh = $this.height();
		$next.each(function(){
			var h = $(this).height();
			if (h > maxh) maxh = h;
		});
		$next.andSelf().height(maxh);
    });
	
	// equal height for partners
	/*
	$("#partnerlist > li:odd").each(function(index,element){
		var $this = $(this);
        var $prev = $this.prev("li");
		var maxh = $this.height() > $prev.height() ? $this.height() : $prev.height();
		$prev.andSelf().height(maxh);
		$(this).css("margin-right",0);
    });
	//$("#partnerlist > li:odd").css("margin-right",0);
	$("#partnerlist > li:lt(2)").addClass("firstrow");
	$("#partnerlist > li:last").prev().andSelf().addClass("lastrow");
	*/
	
	//where to buy
	$("#where2buy").each(function(){
		var $address = $("#address");
		var $partnertype = $("#partnertype");
		var $button = $address.nextAll(".submit");
		var $results = $("#addressresult");
		var shopUrl = "/forgalmazok/cimkereso/";
		var defaultText = "Az Ön címe...";

		var geocoder = new google.maps.Geocoder();
		if (geocoder) {
			$button.click(function(e){
				e.preventDefault();
				var address = $address.val();
				if (address != defaultText && address != "" ) {
					var partnertype = $partnertype.val() == "" ? "" : "&type=" + $partnertype.val();
					geocoder.geocode({ 'address': address, 'language': 'hu', 'region': 'hu' }, function (results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							if (results.length > 1) {
								var htmlFrag = "<p>Kérjük pontosítsa a címet!</p><ul>";
								for (i=0;i<results.length;i++) {
									htmlFrag += "<li><a href='"+shopUrl+"?lat="+results[i].geometry.location.lat()+"&lng="+results[i].geometry.location.lng()+partnertype+"'>" + results[i].formatted_address; + "</a></li>";
								}
								htmlFrag += "</ul>"; 
								$results.html(htmlFrag);
							} else {
								//alert("goto: "+shopUrl+"?lat="+results[0].geometry.location.lat()+"&lng="+results[0].geometry.location.lng());
								window.location.href = shopUrl + "?lat="+results[0].geometry.location.lat()+"&lng="+results[0].geometry.location.lng()+partnertype;
							}
						} else {
							$results.html("<p>A keresett cím nem található!</p>");
						}
					});
				}
				return false;
			});
			$address.keyup(function(event){
			  if(event.keyCode == 13){
				$button.click();
			  }
			});

		}		
		
	});
	
	// Google map results
	$("#mapcanvas").each(function(){

		var mapcenter = new google.maps.LatLng(47.162490,19.33304);
		var bounds = new google.maps.LatLngBounds();
		
		var mapOptions = {
		  zoom: 7,
		  center: mapcenter,
		  mapTypeId: google.maps.MapTypeId.ROADMAP,
		  language: "hu"
		};
		var map = new google.maps.Map(this, mapOptions);
		var infowindow = new google.maps.InfoWindow();
		
		$("#gmaplist address").each(function(index,element){
			var $this = $(this);
			var image = '/assets/images/markers/marker'+(index+1)+'.png';
			var latlng = new google.maps.LatLng($this.data("lat"),$this.data("lng"));
			var title = $this.children("h3").text();
			var props = $('<div>').append($this.children(".properties").clone()).remove().html();
			var markercontent = "<div><strong>"+title+"</strong></div>"+props+$this.find("dd:eq(0)").text()+"<br />"+$this.find("dd:eq(1)").text();
			var shadow = new google.maps.MarkerImage("/assets/images/markers/shadow.png",
			       new google.maps.Size(51.0, 37.0),
				   new google.maps.Point(0, 0),
				   new google.maps.Point(17.0, 37.0)
			);
			var marker = new google.maps.Marker({
				position: latlng, 
				map: map,
				icon: image,
				title: $this.children("h3").text(),
				shadow: shadow
			});

			//init info window
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setContent(markercontent);
				infowindow.open(map, marker);  
			});

			// extend bounds with the marker position
			bounds.extend(latlng);
		});

		// process url params
		var urlLat = parseFloat($.urlParam("lat"));
		var urlLng = parseFloat($.urlParam("lng"));
		var urlLoc = unescape($.urlParam("loc"));
		
		if (urlLoc !== "" && urlLoc !== "0") {
			var geocoder = new google.maps.Geocoder();
			if (geocoder) {
				geocoder.geocode({ 'address': urlLoc, 'language': 'hu', 'region': 'hu' }, function (results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						var latlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
						var centermarker = new google.maps.Marker({
								position: latlng, 
								map: map,
								icon: '/assets/images/markers/your-location.png',
								title: 'Választott hely.',
								clickable: false
						});
						bounds.extend(latlng);
						map.fitBounds(bounds);
					}
				});
			}
		}
		if (urlLat !== 0 && urlLng !== 0) {
			var latlng = new google.maps.LatLng(urlLat,urlLng);		
			if (latlng) {
				var centermarker = new google.maps.Marker({
						position: latlng, 
						map: map,
						icon: '/assets/images/markers/your-location.png',
						title: 'Az Ön pozíciója.',
						clickable: false
				});
				bounds.extend(latlng);
			}		
		}
		map.fitBounds(bounds);
		$("#maploader").remove();

	});
	
	// partner list masonry
	$('#gmaplist').each(function(){
		var $this = $(this);
		$this.imagesLoaded(function(){
			$this.masonry({
				itemSelector : 'address'
			});
		});
	});
	// partner search masonry
	$('#partnerlist').each(function(){
		var $this = $(this);
		$this.imagesLoaded(function(){
			$this.masonry({
				gutterWidth: 40
			});
		});
	});
	
	// tabs
	$(".tabs").each(function() {
		$(this).prepend("<ul></ul>");
		var $tabtitles = $(".tabcontent > h2");
		//$("a",$tabtitles).each(function(){ $(this).attr("href","#"+this.hash.slice(1)); });
		$tabtitles.contents().unwrap().prependTo($(this).children("ul")).wrap("<li></li>");
		
		if(document.location.hash){ $.scrollTo(0); }
		
		$(this).tabs({
			fx: { opacity: 'toggle' },
			select: function(event, ui) {
					jQuery(this).css('height', jQuery(this).height());
					jQuery(this).css('overflow', 'hidden');
					window.location.hash = ui.tab.hash;
			},
			show: function(event, ui) {
					jQuery(this).css('height', 'auto');
					jQuery(this).css('overflow', 'visible');
			}
		});
	});

	// lightBox
	$("figure.product").each(function(){
		var $figure = $(this);
		$("a:first",this).lightBox({
			txtImage: '',
			txtOf: ' / ',
			imageLoading:	'/assets/images/lightbox-ico-loading.gif',
			imageBtnPrev:	'/assets/images/lightbox-btn-prev.gif',
			imageBtnNext:	'/assets/images/lightbox-btn-next.gif',
			imageBtnClose:	'/assets/images/lightbox-btn-close.gif',
			imageBlank:		'/assets/images/lightbox-blank.gif'		
		});
		$("a:gt(0)",this).click(function(e){		
			var $bigLink = $("a:first",$figure);
			var $bigImg = $bigLink.children("img");
			var $this = $(this);
			var $img = $this.children("img");
			var href = $this.attr("href");
			var title = $this.attr("title");
			var src = $img.attr("src");
			var alt = $img.attr("alt");
			
			$bigImg.stop(true,true).fadeOut(200);
			$img.stop(true,true).fadeOut(200);
			
			$this.attr({ 'href': $bigLink.attr("href"), 'title': $bigLink.attr("title") });
			$img.attr({ 'src': $bigImg.attr("src"), 'alt': $bigImg.attr("alt") });
			$bigLink.attr({ 'href': href, 'title': title });
			$bigImg.attr({ 'src': src, 'alt': alt });

			$bigImg.fadeIn(200);
			$img.fadeIn(200);

			return false;
		});
	});

	// orderForm
	$("#order-form").each(function(){
		$( "#order-form" ).dialog({
			autoOpen: false,
			height: 'auto',
			width: 500,
			modal: true
		});
		$( "#order-button" )
			.click(function() {
				$( "#order-form" ).dialog( "open" );
		});
	});

	//slides
	$("#slides").each(function(){
		if ($(".slide",this).length>1) {
			$(this).slides({
				preload: true,
				preloadImage: '/assets/images/loading.gif',
				play: 6000,
				pause: 2000,
				slideSpeed: 1000,
				hoverPause: true
			});
		} else {
			$(".slides_container",this).show();		
		}
	});

	// Multi column
	/*
	$(".multicolumn").each(function(){
		$("table",this).addClass("dontsplit");
		$(this).columnize({ columns: 2, lastNeverTallest: true });
	});
	*/

	/* submenu */
    $("#submenu > ul > li:has(.active)").addClass("traversal");
	$("#submenu > ul > li > span").click(function(){
		$(this).next("ul").slideToggle(200);
		$(this).parent().toggleClass("traversal");
	});

});
