var relativeUri = location.href.replace(/^http:\/\/.*?\//, '/').replace(/\/$/, '');

if ($.mask)
	$.mask.definitions['0']='[ 0-9]';

var closableFloatMenu = null;

$.extend({
	/*
	 * Response processor
	 *
	 * @param object event_root
	 */
	responseProcessor: function(event_root)
	{
		/* Info label */
			$('#username_label, #password_label, #txtSearch_label', event_root).labelOver();

		/* Alternate rows */
			$('ul.products, .recent_products-box ul, ul.check, .cart ul, .order-details .item', event_root).each(function(i){
				$('li:odd', this).addClass('alter');
			});
			$('.workshop-table tbody tr:odd', event_root).addClass('alter');

		/* Tooltips */
			$('.tooltipped', event_root).tooltip({
				extraClass: 'ui-corner-all',
			    bodyHandler: function() {
			        return $(this).next().html();
			    },
			    showURL: false
			});


		/* Add-to-cart */
			$('.btnCart', event_root).click(function() {
				var productId = $.id_from_href(this);
				if ($(this).hasClass('refreshPage'))
				{
				    if ($(this).hasClass('fourmore')) {
                                        $.post('/index/add-to-cart', {id: productId, darab: 3}, function(data){
                                            location.href = "/megrendeles";
                                            //location.reload(true);
                                        }, 'json');
                                    }
                                    else if ($(this).hasClass('three')) {
                                        $.post('/index/add-to-cart', {id: productId, darab: 2}, function(data){
                                            location.href = "/megrendeles";
                                            //location.reload(true);
                                        }, 'json');
                                    }
                                    else if ($(this).hasClass('pack_order')) {
                                        $.post('/index/add-to-cart?show_error=1', {id: productId, pack_order: 1}, function(data){
                                            location.href = "/megrendeles";
                                            //location.reload(true);
                                        }, 'json');
                                    }
                                    else if ($(this).hasClass('delPrint')) {
                                        $.post('/index/add-to-cart', {id: productId, delprint: 1}, function(data){
                                            location.href = "/megrendeles";
                                            //location.reload(true);
                                        }, 'json');
                                    }
				    else if ($(this).hasClass('lp')) {
                                        $.post('/index/add-to-cart', {id: productId, delprint: 1}, function(data){
                                            location.href = "/megrendeles";
                                            //location.reload(true);
                                        }, 'json');
                                    }
                                    else {
                                        $.post('/index/add-to-cart', {id: productId}, function(data){
                                            location.reload(true);
                                        }, 'json');
                                    }
				}
				else
				{
					$.post('/index/add-to-cart', {id: productId}, $.process_response, 'json');
				}
				_gaq.push(['_trackPageview', '/kosar/termek-hozzaadas/'+productId]);
				return false;
			});

		/* Remove from cart */
			$('.btnRemoveCart', event_root).click(function(){
				var productId = $.id_from_href(this);
				$.post('/index/remove-from-cart', {id: productId}, $.process_response, 'json');
				_gaq.push(['_trackPageview', '/kosar/termek-kivetel/'+productId]);
				return false;
			});

		/* Panel close button */
			$('.btnContinue', event_root).click(function(){
				$.close_lightmodal();
				return false;
			});
			$('.close-lightbox', event_root).click(function(){
				$.close_lightmodal();
			});

		/* Page rotators */
			$('.rotator', event_root).rotator();

		/* YouTube links */
			$('.btnYouTubeVideo', event_root).click(function(){
				$.lightmodal($(this).next().clone(true));
				return false;
			});

		/* Pop-up ajax */
			$('.lb-popup', event_root).click(function(){
				$.get($(this).attr('href'), function(data){
					$.lightmodal('<div class="scroll-box">'+data+'</div>');
					$.responseProcessor($('#modalContentPadding'));
				});
				return false;
			});

		/* Pop-up article */
			$('.lb-text', event_root).click(function(){
				var id = $.id_from_href(this);
				$.get('/index/get-article/id/'+id, function(data){
					$.lightmodal('<div class="scroll-box">'+data+'</div>');
					$.responseProcessor($('#modalContentPadding'));
				});
				return false;
			});

                /* Pop-up termekertekeles */

                        $('.lb-form', event_root).click(function(){
				var id = $.id_from_href(this);
				$.get('/index/get-ertekeles/id/'+id, function(data){
					$.lightmodal('<div class="scroll-box">'+data+'</div>');
					//$.responseProcessor($('#modalContentPadding'));
				});
				return false;
			});

		/* Drop-down article */
			$('.dd-text', event_root).click(function(){
				var $parent = $(this).parent();
				var itemToAppendTo = this;
				if (
					$parent.children().length == 1 ||
					$parent.tagName == 'h1' ||
					$parent.tagName == 'h2' ||
					$parent.tagName == 'h3' ||
					$parent.tagName == 'h4' ||
					$parent.tagName == 'h5' ||
					$parent.tagName == 'h6'
					)
					itemToAppendTo = $parent.get(0);

				if (itemToAppendTo.isDroppedDown)
				{
					$(itemToAppendTo).next().slideToggle();
				}
				else
				{
					itemToAppendTo.isDroppedDown = true;
					var $link = $(this);
					var id = $.id_from_href(this);
					$.get('/index/get-article/id/'+id, function(data){
						var $text = $('<div class="dropped-text" style="display: none;">'+data+'</div>');
						$(itemToAppendTo).after($text);
						$.responseProcessor($text);
						$text.slideDown('fast');
					});
				}
				return false;
			});

		/* Workshop dates */
			$('.workshopDates', event_root).each(function(){
				var $this = $(this);
				var workshopDays = [];
				var show_date = null;

				$('a', this).each(function(i){
					var $a = $(this);
					var ws_date = $.string_to_date($a.attr('title').replace(/\s\|.*/, ''));
					this.wsDate = ws_date;
					if (i == 0)
						show_date = ws_date;
					workshopDays[i] = ws_date;
					/*$a.hover(function(){
						$this.datepicker('setDate', this.wsDate);
					});*/
				});

				$this.datepicker({
					numberOfMonths: 3,
					defaultDate: show_date,
					beforeShowDay: function(date)
					{
						index = -1;
						$(workshopDays).each(function(i){
							if (
								workshopDays[i].getDate() == date.getDate() &&
								workshopDays[i].getMonth() == date.getMonth() &&
								workshopDays[i].getYear() == date.getYear()
							)
							{
								index = i;
							}
						});
						if (index == -1)
							return [false, ''];
						return [true, 'workshopDate'];
					},
					onSelect: function(dateText, inst)
					{
						var selDate = $.string_to_date(dateText);
						var ordered = false;
						$('a', $this.get(0)).each(function(i){
							if ( !ordered &&
								selDate.getDate() == this.wsDate.getDate() &&
								selDate.getMonth() == this.wsDate.getMonth() &&
								selDate.getYear() == this.wsDate.getYear()
							)
							{
								ordered = true;
								$(this).click();
							}
						});
					}
				});
			});


		/* Search page */
			$('.chkTopicAll', event_root).each(function(i){
				var chkAll = this;
				this.allTopicsChecked = true;
				$(this).click(function(){
					chkAll.allTopicsChecked = !chkAll.allTopicsChecked;
					$('.chkTopic', $(this).parents('.chkTopicItems')).each(function(){
						$(this).attr('checked', chkAll.allTopicsChecked);
						$(this).change();
					});
				});
			});

		/* Tabs */
			$(".tabs", event_root).each(function(i){
				var $tabs = $(this);
				$('a', $tabs).each(function(i){
					$($(this).attr('href')).hide();
				});
				$('a', $tabs).click(function(event){
					$($('a.active', $tabs).attr('href')).hide();
					$('a', $tabs).removeClass('active');
					$(this).addClass('active').addClass('ui-corner-top');
					$($(this).attr('href')).show();
					_gaq.push(['_trackPageview', relativeUri + $(this).attr('href').replace('#', '/')]);
                    ghmxy_click(event);
					return false;
				});
				if ($('.active', this).length == 0 && $('a', this).length > 0)
					$($('a', this).get(0)).addClass('active');
				//$('a:first', $tabs).click();
			});

		/* Show the first form-tab */
			$('.form-tab:first', event_root).show();
			$('.category-tab ul.tabs li a', event_root).click(function(){
				var $forms = $($(this).attr('href').replace('tab', 'forms'));
				$forms.parent().children('.form-tab').hide();
				$forms.show();

				var $dps = $($(this).attr('href').replace('tab', 'discount_products'));
				$dps.parent().children('.form-tab').hide();
				$dps.show();
				_gaq.push(['_trackPageview', relativeUri + $(this).attr('href').replace('#', '/')]);
			});
			//$('.form-tab:first ul.tabs li:first a', event_root).click();

		/* Simulate click on every first-tab */
			$('.tabs', event_root).each(function(){
				$('li:first a', this).click();
			});

		/* Check-filter */
			$('.chkTopic', event_root).change(function(){
				var subtopic_id = $(this).attr('name').replace('chkTopic', '');
				if ($(this).attr('checked'))
					$('.subtopic-'+subtopic_id).show();
				else
					$('.subtopic-'+subtopic_id).hide();
			});

		/* Scroll to anchor */
			$('.scroll-link', event_root).click(function(){
				$(document).scrollTo($(this).attr('href'), 500);
				return false;
			});

		/* Masked inputs */
			if ($.mask)
			{
				$('.tel', event_root).mask('+99 (00) 999-9999 / 0000');
				$('.fax, .mobile', event_root).mask('+99 (00) 999-9999');
			}

		/* Choose to show items */
			$('.chooseShowable', event_root).hide();
			$('.chooseShow', event_root).click(function(){
				$(this).siblings('.active-show').removeClass('active-show');
				$(this).siblings('.chooseShow').addClass('active-hide');
				$(this).removeClass('active-hide');
				$(this).addClass('active-show');
				var $item = $($(this).attr('href'));
				$item.siblings('.chooseShowable').slideUp('fast', function(){
					$item.slideDown('fast', function(){
						$.scrollTo('#'+$item.attr('id'), 500);
					});
				});
				return false;
			});

		/* Map link */
			$('.google-map', event_root).click(function(){
				var address = $(this).attr('title');
				var info = $('img', this).attr('alt');


				if (GBrowserIsCompatible())
				{
					var mapData = '<div id="lb_map"></div>'
					$.lightmodal(mapData);
					var map = new GMap2(document.getElementById("lb_map"), { size: new GSize(670, 450) });
					map.setMapType(G_HYBRID_MAP);

					map.setUIToDefault();

					var geocoder = new GClientGeocoder();
					geocoder.getLatLng(
						address,
						function(point){
							if (point)
							{
								map.setCenter(point, 15);
								var marker = new GMarker(point);
						        map.addOverlay(marker);
						        marker.openInfoWindowHtml(info);
							}
						}
					);

				    // map.setUIToDefault();


				}

				return false;
			});

		/* Product discount ribbons */
			$('.cards .product-discount', event_root).each(function(i){
				$(this).append('<span class="discount-ribbon" style="background-image: url(\'/image/ribbon/text/'+escape($(this).attr('title'))+'\')"></span>')
				$('h4', this).prepend('<span class="discount-spacer">&nbsp;</span>');
			});

                /* Connected product discount ribbons */
			$('.product-discount-conn-prod', event_root).each(function(i){
				$(this).append('<span class="discount-ribbon" style="background-image: url(\'/image/ribbon/text/'+escape($(this).attr('title'))+'\')"></span>')
				$('h4', this).prepend('<span class="discount-spacer">&nbsp;</span>');
			});

		/* Corners */
			$('#txtSearch_container, #username_container, #password_container, .acore-button, .card, .box-content, .product-panel .discount, .product-info-box, .pic-bar, .priceTable, .priceTable div', event_root).addClass('ui-corner-all');
			$('ul#main, ul#main li a.active, ul#main a.home, ul.tabs, ul.tabs li a.active, .half-box .box', event_root).addClass('ui-corner-top');

		/* Search button progress bar */
			$('#btnSearch', event_root).click(function(){
				$('#searchProgress').fadeIn('fast');
			});

		/* Subscribe to multiple newsletters */
			$('.btnSubscribe', event_root).click(function(){
				var items = '';
				var form = $(this).parents('form').get(0);
				var $form = $(form);
				$('input', form).each(function(){
					if ($(this).attr('checked'))
						items += $(this).attr('value') + ',';
				});
				if (items.length == 0)
				{
					alert('Nem jelölt ki hírleveleket!');
					return false;
				}
				else
				{
					$form.attr('action', $form.attr('action') + '/' + items + '/hirlevelekre');
				}
			});

		/* Ajax submit form, and replace it with the response */
			$('form.ajax-submit-replace', event_root).each(function(i){
				var $frm = $(this);
				$frm.ajaxForm({
					success: function(responseText, statusText, xhr, $form){
						$frm.after(responseText);
						$frm.remove();
					}
				});
			});

		/* Coupon checking */
			$('#coupon', event_root).blur(function(){
				var $input = $(this);
				$.get('/marketing/coupon-function/code/'+$(this).val(), function(data){
					$('#couponExplain').remove();
					$input.after(data);
				});
			});

	}
});

//-----------------------------------------------------------------------------------------------

$(document).ready(function(){

	$('body').prepend('<div id="ajaxLoader" class="ui-corner-all"><img src="'+image_base_uri+'sites/Dashofer/images/ajax-loader.gif" alt="Letöltés..." /></div>');

	$(document).ajaxStart(function(){
		$('#ajaxLoader').fadeIn();
	});

	$(document).ajaxStop(function(){
		$('#ajaxLoader').fadeOut();
	});

	$.responseProcessor(document);

	// Search progress
	var imgUrl = image_base_uri+'sites/Dashofer/images/searching.gif';
	$('body').prepend('<div id="searchProgress" style="display: none; position: absolute; position: fixed; z-index: 9998; top: 0; left: 0; width: 100%; height: 100%; background: #aaa; filter: alpha(opacity=90); -moz-opacity:.90; opacity:.90; text-align: center;"><div style="width: 300px; padding: 50px; margin: 200px auto; background: #fff;"><p>A keresés folyamatban, kérjük várjon...</p><img src="'+imgUrl+'" alt="keresés..." /></div></div>');

	/* Header arrows */
		$('h2.block').each(function(i){
			var $this = $(this);
			$this.addClass('ui-corner-all');
			$this.html('<span class="text">'+$(this).html()+'</span><span class="arrow"></span>');
		});

	/* Gallery lightbox */
		$().piroBox({
			my_speed: 600,
			bg_alpha: 0.8,
			radius: 4,
			scrollImage : false,
			pirobox_next : 'piro_next',
			pirobox_prev : 'piro_prev',
			close_all : '.piro_close',
			slideShow : 'slideshow',
			slideSpeed : 6
		});

	/* Float menu */
		$('.float-menu-template').each(function(i){
			var $tpl = $(this);
			var $menu = $('.'+$(this).attr('id'));
			var $menuParent = $menu.parent();
			$menuParent.parent().css('z-index', 4000);
			$menuParent.css('position', 'relative');
			//$menuParent.css('z-index', '3000');
			$menu.mouseenter(function(){

				closeFloatMenu();
				$menu.after('<div id="float_menu" style="display: none; z-index: 1000;"><div class="float-menu-content">'+$tpl.html()+'</div></div>');
				$('#float_menu').get(0).entered = false;
				$('#float_menu').css('left', (-$menuParent.width()+parseInt($tpl.css('left').replace(/\D+/, '')))+'px');
				$('#float_menu').css('top', ($menuParent.height()+parseInt($tpl.css('top').replace(/\D+/, '')))+'px');
				$('#float_menu').css('width', $tpl.css('width'));
				$('#float_menu').css('height', $tpl.css('height'));
				$('#float_menu').fadeIn('fast');
				$('#float_menu').mouseenter(function(){
					this.entered = true;
				});
				$('#float_menu').mouseleave(function(){
					this.entered = false;
					if (!$('#float_menu').hasClass('hovering'))
						closeFloatMenu();
				});

			});
			$menu.mouseleave(function(){
				closableFloatMenu = $('#float_menu').get(0);
				setTimeout('closeFloatMenu();', 200);
			});
		});

	/* Contact map */
		if ($('#map').length > 0 && GBrowserIsCompatible())
		{
			var map = new GMap2(document.getElementById("map"), { size: new GSize(350, 370) });
			//map.setMapType(G_HYBRID_MAP);

			map.setUIToDefault();

			var geocoder = new GClientGeocoder();
			geocoder.getLatLng(
				'1147 Budapest Jávorka Ádám u. 56.',
				function(point){
					if (point)
					{
						map.setCenter(point, 15);
						var marker = new GMarker(point);
				        map.addOverlay(marker);
				        marker.openInfoWindowHtml('<b>Verlag Dashöfer Szakkiadó Kft</b><br />1147 Budapest <i>Jávorka Ádám u. 56.</i>');
					}
				}
			);
		}

	$('#main .products').text('Szakkiadványok');
	$('#main .products').attr('title', 'Szakkönyvek, szaklapok, szoftverek, online szakkönyvek és online szaklapok');
});


function closeFloatMenu()
{
	if (closableFloatMenu)
	{
		var $menu = $(closableFloatMenu);
		if ($menu.length > 0)
		{
			var menu = $menu.get(0);
			if (!menu.entered)
				$menu.fadeOut('fast', function(){ $menu.remove(); });
		}
	}
}

