/**
 *
 * Medvetna presenter
 * Master JavaScript behaviours
 * © 2010
 *
 * @depends jquery-1.4.2.min.js
 * @depends jquery.plugins.min.js
 */

(function($){ 
			
	/**
	 * On DOM ready
	 */
	$(function(){
		
		$('html').removeClass('no-js').addClass('js');
		$('.button').attr('disabled', false);
		
		if($('body').hasClass('thanks')){
			$(this).deleteCookies();
		}

		$('.checkout form').checkout();
		$('.contact form').contact();
		$('body').clientBrowser();
		$('a.external').newWindow();
		$('#cart').cart();
		$('#newsletter-form').newsletter();
		$('.tooltip').tooltip();
		$('.tooltip.left').tooltip({
			orientation: 'left'
		});
		$('#footer-content .social-media, #footer-content .subscribe, #footer-content .newsletter, #footer-content .contact').equalHeight();
		$('li.cat-item-16 a').addClass('small-icon realization');
		$('li.cat-item-3 a').addClass('small-icon recycled');
		$('li.cat-item-4 a').addClass('small-icon ecofriendly');
		$('li.cat-item-21 a').addClass('small-icon charity');
		$('li.cat-item-43 a').addClass('small-icon fairtrade');
		$('#menu-huvudmeny').mainNav();
		$('#left-sidebar .sub-navigation').subNav();
		$('#searchform input, #checkout-form #delivery_message').labelify({
			labelledClass: 'labelHighlight' 
		});
		$('input, textarea').bind('focus', function(){
			$(this).addClass('focus');
		}).bind('blur', function(){
			$(this).removeClass('focus');
		});
		$('input.print').bind('click', function(){
			window.print();
		});
		$('.product-list').clickList();
		if ($('a.resize').length) {
			$('a.resize').fancybox({
				'titleShow' : false
			});
		}
		if ($('a.popup').length) {
			$('a.popup').fancybox({
				'width' : '50%',
				'height' : '70%',
				'autoScale' : false,
				'transitionIn' : 'none',
				'transitionOut' : 'none',
				'type' : 'iframe'
			});
		}
		$('.slideshow').cycle({
			fx:     'scrollHorz', 
			speed:  '800', 
			timeout: 8000,
			pause:   10,
			next:   '#next', 
			prev:   '#prev' 
		});
	});	

	$.fn.deleteCookies = function(options){
		
		// Options
		options = $.extend({
			action: '/wp-content/themes/medvetnapresenter/application/actions.php',
			type: 'POST',
			dataType: 'json',
			actions: 'delete-cookies'
		}, options);

		$.ajax({
			type: options.type,
			url: options.action,
			data: 'action=' + options.actions,
			dataType: options.dataType
		});
		
	}
		
	$.fn.clickList = function(options){
		
		// Options
		options = $.extend({
			linkContainer: 'li',
			linkParent: 'h2',
			clickable: 'p'
		}, options);
		
		$(this).find(options.linkContainer).each(function(){
			var link = $(this).find(options.linkParent + ' a').attr('href');
			var linkTitle = $(this).find(options.linkParent + ' a').attr('title');
			
			$(this).find('p').bind('click', function(){
				window.location = link;
			}).css('cursor', 'pointer');
			
			/*$(this).find('p').wrapInner('<a href="' + link + '" title="' + linkTitle + '"></a>');*/
		});
	
	};
		
	$.fn.mainNav = function(options){
		
		// Options
		options = $.extend({
			style: 'current-menu-item page_item current_page_item'
		}, options);
		
		var elm = $('#main-content').metadata().menu;
		$(this).find(elm).addClass(options.style);
		
	};
		
	$.fn.subNav = function(options) {
	
		// Options
		options = $.extend({
		}, options);
		
		$(this).find('ul li:not(.current-cat, .current-cat-parent) ul').hide();
			
		$(this).find('ul:not(ul.children > li) > li a').bind('click', function(){
			$(this).parent().find('ul').slideToggle('fast');
			if ($(this).parent().find('ul').length == 0) {
				return true;
			} else if ($(this).parent().parent().hasClass('children') == false) {
				return false;
			}
		});
	
	};
		
	$.fn.newsletter = function(options) {
		
		// Options
		options = $.extend({
		}, options);
		
		var response = function(data){
			if(data.feedback == 'success'){
				$('#client-newsletter-success').show();
			} else {
				alert('error');
			}
		};
		
		$(this).validate({
			errorContainer: $(this).parent().find('#client-newsletter-error'),
			errorLabelContainer: $('ul', $(this).parent().find('#client-newsletter-error')),
			wrapper: 'li',
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					success: response,
					dataType: 'json',
					resetForm: true
				});
			}
		});
		
	};	
	
	$.fn.checkout = function(options) {
		
		// Options
		options = $.extend({
		}, options);
		
		$('#other-delivery-form').hide();
		
		$('#other-delivery-address').bind('click', function () {
			if($(this).attr('checked')) {
				$('#other-delivery-form').slideDown('fast');
			} else {
				$('#other-delivery-form').slideUp('fast');
			}
		});
		
		$(this).validate({
			rules: {
				delivery_firstname: {
					required: "#other-delivery-address:checked"
				},
				delivery_lastname: {
					required: "#other-delivery-address:checked"
				},
				delivery_address: {
					required: "#other-delivery-address:checked"
				},
				delivery_zipcode: {
					required: "#other-delivery-address:checked"
				},
				delivery_city: {
					required: "#other-delivery-address:checked"
				}
			},
			errorContainer: $(this).find('#client-order-error'),
			errorLabelContainer: $('ul', $(this).find('#client-order-error')),
			wrapper: 'li'
		});
		
		$(this).submit(function(){
			
			if ($(this).valid()){
				var r = confirm("Nu skickas du till DIBS, öppnas i ett nytt fönster, och en säker uppkoppling så att du kan genomföra köpet");
				if (r != true) {
					return false;
				} else {
					
					$.ajax({
						type: 'POST',
						url: '/wp-content/themes/medvetnapresenter/application/actions.php',
						data: $(this).serialize(),
						dataType: 'json'
					});
					
					window.open('', 'securetransferdibs', 'width=600,height=600,resizeable,scrollbars');
      				this.target = 'securetransferdibs';
				}

			}
			
			
		});
			
	};
		
	$.fn.contact = function(options) {
				
		// Options
		options = $.extend({
		}, options);
		
		var response = function(data){
			if(data.feedback == 'success'){
				$('#client-contact-success').show();
			} else {
				alert('error');
			}
		};
		
		$(this).validate({
			errorContainer: $(this).parent().find('#client-contact-error'),
			errorLabelContainer: $('ul', $(this).parent().find('#client-contact-error')),
			wrapper: 'li',
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					success: response,
					dataType: 'json',
					resetForm: true
				});
			}
		});
		
	};
		
	$.fn.cart = function(options) {
		
		// Options
		options = $.extend({
			currency: 'kr',
			action: '/wp-content/themes/medvetnapresenter/application/actions.php',
			type: 'POST',
			dataType: 'json'
		}, options);
		
		var shortenTitle = function(text, chars) {
			var length = text.length;
			if (length >= chars) {
				text = text.substr(0,17) + '...';
			}
			return text;
		};
		
		var updateCart = function() {
			$('span.cart-loader').delay(1000).fadeOut('fast');
			$('#cart ul.items li').remove();
			eval('var cookie = ' + $.cookie('cart'));
			if ($.cookie('cart')) {
				$.each(cookie, function(index, value){
					var id = value['id'];
					
					var title = value['title'].replace(/\+/g,' ');				
					
					var color = value['color'];
					var size = value['size'];
					var amount = value['amount'];
					var price = value['price'];
					var vat = value['vat'];
					var weight = value['weight'];
					var realization = value['realization'];
					var url = value['url'];
					price = parseInt(price * amount);
					if (realization) {
						var cssClass = 'realization';
					} else {
						var cssClass = '';
					}
					var tooltipTxt = 'Antal: ' + amount + ' st';
					if (color != '') {
						tooltipTxt += '<br />Färg: ' + $.url.decode(color);
					} 
					if (size != '') {
						tooltipTxt += '<br />Storlek: ' + $.url.decode(size);
					}
					$('#cart ul.items').append('<li class="' + cssClass + ' tooltip left {\'title\': \'' + title + '\', \'desc\': \'' + tooltipTxt + '\', \'vat\': \'' + vat + '\', \'weight\': \'' + weight + '\'}"><span class="count">' + amount + ' st</span> <span class="name">' + shortenTitle(title, 20) + '</span> <span class="price" sum="' + price + '">' + CurrencyFormatted(price) + ' ' + options.currency + '</span><a href="#" id="cart-add-item" class="{\'itemid\': \'' + id + '\', \'action\': \'add-to-cart\', \'amount\': \'1\', \'size\': \'' + size + '\', \'color\': \'' + color + '\'}" title="Lägg till">+</a> <a href="#" id="cart-remove-item" class="{\'itemid\': \'' + id + '\', \'action\': \'remove-from-cart\', \'amount\': \'1\', \'size\': \'' + size + '\', \'color\': \'' + color + '\'}" title="Ta bort">-</a> <a href="#" id="cart-delete-item" class="{\'itemid\': \'' + id + '\', \'action\': \'delete-from-cart\', \'size\': \'' + size + '\', \'color\': \'' + color + '\'}" title="Radera">X</a></li>');
				});
				$('#cart p#empty-cart-copy').hide();
				$('#cart ul.items, #cart ul.total, #cart p.buttons').show();	
				calculateCart();
			} else {
				emptyCart();
			}
		};
		
		var emptyCart = function() {
			$('#cart p#empty-cart-copy').show();
			$('#cart ul.items, #cart ul.total, #cart p.buttons').hide();
		};
		
		var displayCartBtn = function() {
			var title = '';
			$('#cart ul.items li').live('mouseover', function(){
				title = $(this).find('span.name').html();
				tempTitle = shortenTitle(title, 20);
				$(this).addClass('active').find('#cart-add-item, #cart-remove-item, #cart-delete-item').show();
				$(this).find('span.price').hide();
				$(this).find('span.name').html(tempTitle);
			}).live('mouseout', function(){
				$(this).removeClass('active').find('#cart-add-item, #cart-remove-item, #cart-delete-item').hide();
				$(this).find('span.price').show();
				$(this).find('span.name').html(title);
			});
		};
		
		var calculateCart = function() {
			var sum = 0;
			var vat = 0;
			var tmpSum = 0;
			var tmpVat = 0;
			$('#cart ul.items li').each(function(){
				tmpSum = parseInt($(this).find('span.price').attr('sum'));			
				tmpVat = parseFloat($(this).metadata().vat);
				if (tmpVat == 0.25) {
					tmpVat = 0.2;
				} else if (tmpVat == 0.06) {
					tmpVat = 0.0566037;
				}
				tmpVat = tmpSum * tmpVat;
				sum += tmpSum;
				vat += tmpVat;
			});
			$('#cart ul.total li.sum span.num').html(CurrencyFormatted(sum) + ' ' + options.currency);
			$('#cart ul.total li.vat span.num').html(CurrencyFormatted(vat) + ' ' + options.currency);
		};
		
		$('form.add-to-cart').each(function(){
			$(this).submit(function(){
				$.ajax({
					type: options.type,
					url: options.action,
					data: $(this).serialize(),
					dataType: options.dataType,
					success: updateCart
				});
				$(this).find('span.cart-loader').show();
				return false;
			});
		});
		
		$('#cart-add-item, #cart-remove-item, #cart-delete-item, #empty-cart').live('click', function(){
			var action = $(this).metadata().action;
			if (action == 'add-to-cart') {
				var itemid = $(this).metadata().itemid;
				var amount = $(this).metadata().amount;
				var color = $(this).metadata().color;
				var size = $(this).metadata().size;
				$.ajax({
					type: options.type,
					url: options.action,
					data: 'action=' + action + '&itemid=' + itemid + '&amount=' + amount + '&color=' + color + '&size=' + size,
					dataType: options.dataType,
					success: updateCart
				});
			} else if (action == 'remove-from-cart'){
				var itemid = $(this).metadata().itemid;
				var amount = $(this).metadata().amount;
				var color = $(this).metadata().color;
				var size = $(this).metadata().size;
				$.ajax({
					type: options.type,
					url: options.action,
					data: 'action=' + action + '&itemid=' + itemid + '&amount=' + amount + '&color=' + color + '&size=' + size,
					dataType: options.dataType,
					success: updateCart
				});
			} else if (action == 'delete-from-cart'){
				var itemid = $(this).metadata().itemid;
				var color = $(this).metadata().color;
				var size = $(this).metadata().size;
				$.ajax({
					type: options.type,
					url: options.action,
					data: 'action=' + action + '&itemid=' + itemid + '&color=' + color + '&size=' + size,
					dataType: options.dataType,
					success: updateCart
				});
			} else if (action == 'empty-cart'){
				$.ajax({
					type: options.type,
					url: options.action,
					data: 'action=' + action,
					dataType: options.dataType,
					success: updateCart
				})
			}
			return false;
		});
						
		updateCart();
		displayCartBtn();
		
	};
	
	function CurrencyFormatted(amount) {
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	}
	
})(jQuery);
