/*			Atlantic Higienia JS
		(c) 2010 Insolis Solutions
	----------------------------------
*/

// Image preloader (this is a jQuery plugin)
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img'); // Creating a DOM element
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

// Do the actual preloading
jQuery.preLoadImages("/img/close_cart.png", "/img/work_anim.gif", "/img/cart_ajax.gif","/img/work.png", "/img/usage_ipari_tisztitas.jpg", "/img/usage_auto_tisztitas.jpg","/img/usage_intezmeny_higienia.jpg","/img/usage_konyha_higienia.jpg");

// Execute to rotator plugin on the given class
$(function () {
	$('ul.rotator').simpleListRotate();
});

// Rotator plugin
(function ($) {
	
	$.fn.simpleListRotate = function (limit, interval) {
		limit = limit || 1; // set the limit
		interval = interval || 8000; // set the interval
	
    	return this.each(function () {
        
        	var $list = $(this),
            	items = [], // cache container
            	currentItem = limit, // current item is the limit
            	total = 0, // initalise this later on
	            width = $list.find('> li:first').width(); // store the width of the first element
            
	        // cache the current list and wrap every list element's html into a li element
        	$list.find('> li').each(function () {
            	items.push('<li>' + $(this).html() + '</li>');
        	});
                            
        	// store the total number of elements     
        	total = items.length;
                            
        	// cut off every element beside the limit
        	$list.find('> li').filter(':gt(' + (limit) + ')').remove();

        	function pushit() {
                                                            
            	// insert a new element from the list cache to the left
            	var $insert = $(items[currentItem]).css({
                	width : 0,
                	opacity : 0,
                	display : 'none'
            	}).prependTo($list);
                        
            	// animate the last li element's opacity to zero            
            	$list.find('> li:last').animate({ opacity:0}, 1000, function () {  
            		// animate the newly inserted first li's width and opacity
            		$insert.animate({ width : width }, 1000).animate({ opacity : 1 }, 1000);
                	// remove the last one, sigh...
                	$(this).remove();                  
            	});
                                
            	// move the current item pointer
            	currentItem++;
                                

            	// if the pointer is greater than or equals to our total number of elements...
            	if (currentItem >= total) {
                	// set the pointer back to zero (first element in the list)
                	currentItem = 0;
            	}
                                
            	// execute all of our code above within the given time-frame
            	setTimeout(pushit, interval)
        	}
        
        	// call the script for the first time
        	pushit();
    	});
	};
})(jQuery);
			

// Menu animator script (not a plugin, what? do you think I'M A JOKE?)
$(document).ready(function() {
	// unleash this ONLY when the DOM structure is fully loaded
	
	// Jump to the heading
	if ($('#heading').length > 0 && window.location.href.indexOf('#') == -1) {
		if ($('#promotion_rotator').length > 0) {
			window.scrollTo(0, 420);
		}
		else {
			window.scrollTo(0, 160);
		}
	}
				
	// do some CSS magic with the submenus
	$('ul.submenu').css({
		position : 'relative',
		marginTop: 0,
		opacity: 0,
		display: 'none'
	}).parent().css({
		height : 95 // set back the container FIR-powered element's height to 95px
	});
				
	// just before we kick off with the hover do some positioning
	$('ul.submenu').each(function() {
		var $submenuHeight = $(this).outerHeight(),
			$parentHeight = $(this).parent().outerHeight();
					
		$(this).css({ top: - ($submenuHeight - ($parentHeight/2)) });
						
	});				
				
	// here we go with the hover function
	$('ul.submenu').parent().each(function() {
				
		var $submenu_trigger = $(this);
					
		if (!$.browser.msie) {
		
			$submenu_trigger.hover(function(){
				$(this).children('ul.submenu').stop().css({display: 'block'}).animate({ opacity: 1}, 500);
			}, function () {									
				$(this).children('ul.submenu').stop().animate({ opacity: 0}, 400,function() {
					$(this).css({display: 'none'});
				});				
			});
		
		}
						
	});
				
	// Shopping cart management
	// Animations, supporting functions
				
	// introducing the new slidefadetoggle
	jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
		return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
	};
				
	// handling all the basic stuff with the cart
	
	$.atlantic_cart_manager = {
		lockAjaxUpdates : "0", // we need to set this global variable to ensure not updating the cart while we are doing operations
		periodicalUpdates : null // container for setTimeout
	};
				
	// hiding the cart
	$('div#cart').hide();
				
	// toggle function
	$('a#cart_open').live('click', function() {
		
		$('div#usage_categories').slideUp(300);
		
		$('div#cart').slideFadeToggle(600, function() {
		
			if ( $('div#cart').is(':visible') == true) {
		
			$('a#cart_open').replaceWith('<a href="#" id="cart_open" title="Kosár bezárása"><img src="/img/close_cart.png" alt="Kosár bezárása" /></a>');
		
			} else {
		
				$('a#cart_open').replaceWith('<a href="#" id="cart_open" title="Kosár megnyitása"><img src="/img/open_cart.png" alt="Kosár megnyitása" /></a>');
		
			}
		
		});	
		
		return false;
					
	});
	
	// products by usage areas slider
	$('li#termekek a').click(function() {
	
		$('div#cart').slideUp(300);	// closing the cart (even if it's closed, hah)
		$('a#cart_open').replaceWith('<a href="#" id="cart_open" title="Kosár megnyitása"><img src="/img/open_cart.png" alt="Kosár megnyitása" /></a>');
		$('div#usage_categories').slideFadeToggle(300); // sliding the overlapping div down
		
		return false;
	
	});
				
	// removing items from the cart
	$('td.cart_item_delete a').live('click', function(event) {
	
		clearTimeout($.atlantic_cart_manager.periodicalUpdates);
	
		$.atlantic_cart_manager.lockAjaxUpdates = "1";
	
		var $target = $(event.target), // we set a reference for the element that triggered the action to use later on
			$cartItemCount = $('table#shoppingcart').children().children('tr').size(); // get the number of elements inside the cart
			
		if (($cartItemCount -2) <= 1 ) {
			$partsToHide = $('table#shoppingcart'); // if we are about to remove the last item, then remove the whole table
		} else {
			$partsToHide = $target.parents('tr'); // ... or if this is not the case then remove just the table-row
		}
				
		// gets the exact href attribute of the link
		var $removalString = $(this).attr('href');
		
		// show the tricky ajax loading circle
		$partsToHide.children('td.cart_item_thumbnail').empty().append('<img src="http://atlantichigienia.hu/img/cart_ajax.gif" />');
		
		$.ajax({ url : $removalString, data: 'ajax=1', success: function(data) {
		
			// slowly change the opacity down to zero, then remove the corresponding element		
			$partsToHide.animate({ opacity: 0},1000, function() {
				
				$(this).remove();
				
				// then we're reloading the cart's inner contents
				$('div#cart').load('/cart.php div#cart_inner', function(response, status, xhr) {

					// there was an error handling the request
					if (status == "error") {
						location.reload(); // since we don't want to display errors we're just reloading the page
					}
					
					// reloading the cart manager and it's contents
					$('div#cart_manager').load('/cart-manager.php div#cart_manager > *', function(response, status, xhr) {
						
						// there was an error handling the request
						if (status == "error") {
							location.reload(); // since we don't want to display errors we're just reloading the page
						}
						
						$.atlantic_cart_manager.periodicalUpdates = setTimeout(updateCart,30000);
						
						$.atlantic_cart_manager.lockAjaxUpdates = "0";
						
						if ( $('div#cart').is(':visible') == true) {
		
							$('a#cart_open').replaceWith('<a href="#" id="cart_open" title="Kosár bezárása"><img src="/img/close_cart.png" alt="Kosár bezárása" /></a>');
		
						}
						
					});	
				});
			});
			
		}});
							
		return false;
				
	});
	
	$('a.add_item_to_cart_btn').live('click',function(event) {
	
		clearTimeout($.atlantic_cart_manager.periodicalUpdates);
		
		var $workerToReplace = this,
			$clickedTarget = $(event.target).parent().parent();
	
		$.atlantic_cart_manager.lockAjaxUpdates = "1";
		
		// gets the exact href attribute of the link
		var $additionString = $(this).attr('href');
		
		if ($(this).hasClass('addtocart_subpage')) {
		
			$(this).replaceWith('<img src="/img/work.png" alt="Dolgozom" title="" style="display: block; margin: 0 auto 0 auto; text-align: center;" class="work_btn" />');
		
		} else {
		
			$(this).replaceWith('<img src="/img/work_anim.gif" alt="Dolgozom" title="" style="display: block; margin: 0 auto 0 auto; text-align: center;" class="work_btn" />');
		
		}
		
		$.ajax({ url : $additionString, data: 'ajax=1', success: function(data) {
		
			$.atlantic_cart_manager.lockAjaxUpdates = "0";
			updateCart();
			
			$clickedTarget.find('.work_btn').replaceWith($workerToReplace);
			
			$('div#notifications').fadeIn(1200).fadeTo(3500,1).fadeOut(1200);
		
		}});		

		
		return false;
	
	});
	
	// updating the cart view periodically
	function updateCart() {
		
		if($.atlantic_cart_manager.lockAjaxUpdates < 1) {
			
			$('div#cart').load('/cart.php div#cart_inner', function(response, status, xhr) {

					// there was an error handling the request
					if (status == "error") {
						location.reload(); // since we don't want to display errors we're just reloading the page
					}
					
					// reloading the cart manager and it's contents
					$('div#cart_manager').load('/cart-manager.php div#cart_manager > *', function(response, status, xhr) {
						
						// there was an error handling the request
						if (status == "error") {
							location.reload(); // since we don't want to display errors we're just reloading the page
						}
						
						$('td.cart_item_quantity input').each(function() { 
							$(this).attr('disabled',true);
						});
						
						if ( $('div#cart').is(':visible') == true) {
		
							$('a#cart_open').replaceWith('<a href="#" id="cart_open" title="Kosár bezárása"><img src="/img/close_cart.png" alt="Kosár bezárása" /></a>');
		
						}
						
						$.atlantic_cart_manager.lockAjaxUpdates = "0";
					});	
			});
						
		}
		
		$.atlantic_cart_manager.periodicalUpdates = setTimeout(updateCart,30000);
	}
	
	// quantity handling
	
	// decreasing the quantity
	$('a.cart_item_q_minus').live('click',function(event) {
	
		clearTimeout($.atlantic_cart_manager.periodicalUpdates);
		
		$.atlantic_cart_manager.lockAjaxUpdates = "1";
		
		$(this).next('input').val(function(index, value) { 
		
			if((value-1) < 1) {
				return value;
			} else {
				return value-1;
			}
			
		});
		
		// gets the exact href attribute of the link
		var $decreaseString = $(this).attr('href');
		
		// AJAX spinner
		$(this).parents('tr').children('.cart_item_thumbnail').empty().append('<img src="http://atlantichigienia.hu/img/cart_ajax.gif" />');
				
		$.ajax({ url : $decreaseString, data: 'ajax=1', success: function(data) {

			$.atlantic_cart_manager.lockAjaxUpdates = "0";
			updateCart();	
		}});
		
		

		return false;
	
	});
	
	// increasing the quantity
	$('a.cart_item_q_plus').live('click',function(event) {
	
		clearTimeout($.atlantic_cart_manager.periodicalUpdates);
		
		$.atlantic_cart_manager.lockAjaxUpdates = "1";
		
		$(this).prev('input').val(function(index, value) { 
				return ++value;
		});
		
		// gets the exact href attribute of the link
		var $increaseString = $(this).attr('href');
		
		// AJAX spinner
		$(this).parents('tr').children('.cart_item_thumbnail').empty().append('<img src="http://atlantichigienia.hu/img/cart_ajax.gif" />');
		
		$.ajax({ url : $increaseString, data: 'ajax=1', success: function(data) {

			$.atlantic_cart_manager.lockAjaxUpdates = "0";
			updateCart();	
		}});
		
		

		return false;
	
	});
	
	// disable the input boxes, since we don't really need them
	$('td.cart_item_quantity input').each(function() { 
		$(this).attr('disabled',true);
	
	});

	// run the update function for the first time
	updateCart();
				
}); // this is the end of everything...

function emailAddress(email) {
	document.write('<a href="mailto:' + email + '">' + email + '</a>');
}
