/**
 * CNSlider
 *
 * Required settings:
 *  display   - provide number of items displayed at once
 *
 * Other settings:
 *  time      - transition time
 *  easing    - easing for the transition
 *  width     - width of the scrolled area (by default visible area + right margin on the last visible item)
 *  previous  - previous link text
 *  next      - next link text
 *  wrap      - wrap container selector
 *  slider    - items container selector
 *  items     - items selector
 */ 

(function($) {
	jQuery.fn.CNSlider = function(options){
		var defaults = {
			width     : 0,
			display   : 6,			
			time      : 500,
			easing    : 'swing',			
			previous  : 'Previous',
			next      : 'Next',
			wrap      : 'div.wrapper',
			slider    : 'ul.items',
			items     : 'ul.items li'
		};
		
		var settings = $.extend({}, defaults, options);
		
		return this.each(function(){
			var $root     = $(this);
			var $wrap     = $root.find(settings.wrap);
			var $slider   = $root.find(settings.slider);
			var $items    = $root.find(settings.items);
			
			var all     = $items.size();
			var pages   = Math.ceil(all/settings.display);
			
			// check is there enough items for paging
			if($items.size() <= settings.display) {
				return false;
			}
			
			// try to estimate visible area width if not set
			var width = settings.width;
			if(settings.width === 0) {
				width = $wrap.width() + parseInt($items.css('margin-right'),10);
			}
			
			// defaults
			var current = 1;
			
			// insert paging links
			$root.append('<ul class="index"><li class="prev"><a href="#previous" class="off">'+settings.previous+'</a></li><li class="next"><a href="#next">'+settings.next+'</a></li></ul>');
			var $controls = $root.find('ul.index');

			// check for first/last page and indicate that in controls
			var check = function(){
				if(current === 1){
					$controls.find('li.prev a').addClass('off');
				} else {
					$controls.find('li.prev a').removeClass('off');
				}
				
				if(current === pages){
					$controls.find('li.next a').addClass('off');
				} else {
					$controls.find('li.next a').removeClass('off');
				}
			};
			
			// add events
			$controls.find('a').click(function(){
				var 
					move,
					direction = $(this).parent().attr('class');
					
				if($slider.is(':animated') || (current == 1 && direction == 'prev') || (current == pages && direction == 'next')) {
					return false;
				}
				
				if(direction == 'next'){
					move = '-='+width+'px';
					current++;
				} 
				else {
					move = '+='+width+'px';
					current--;
				}					
				
				$slider.animate({'marginLeft': move}, settings.time, settings.easing);
				check();
				
				return false;
			});
		});
	};
})(jQuery);

/**
 * Compact labels plugin
 */
(function($){$.fn.compactize=function(inputField){return this.each(function(){var label=$(this),input=inputField||$('#'+label.attr('for'));input.focus(function(){label.hide();}).blur(function(){if(input.val()===''){label.show();}});window.setTimeout(function(){if(input.val()!==''){label.hide();}},50);});};})(jQuery);

/*
 * hrefID jQuery extention - returns a valid #hash string from link href attribute in Internet Explorer
 */
(function($){$.fn.extend({hrefId:function(){return $(this).attr('href').substr($(this).attr('href').indexOf('#'));}});})(jQuery);

/*
 * Scripts
 *
 */
var Engine = {
	utils : {
		links : function(){
			$('a[rel*=external]').click(function(e){
				e.preventDefault();
				window.open($(this).attr('href'));						  
			});
		},
		mails : function(){
			$('a[href^=mailto:]').each(function(){
				var mail = $(this).attr('href').replace('mailto:','');
				var replaced = mail.replace('/at/','@');
				$(this).attr('href','mailto:'+replaced);
				if($(this).text() == mail) {
					$(this).text(replaced);
				}
			});
		},
		labels : function(){
			$('.newsletter form label, .shopping-cart-form .shipping-wrapper label, .checkout-intro form label, .checkout .customers form p label, .access-a label').compactize();
		},
		/**
		 * Creates a new lightbox. 
		 * In case another lightbox already exists, it is being pushed under the overlay
		 */
		lightbox : function(options){
			var overlay = $('#byb-overlay');
			
			options.callback = options.callback || function(){};
			
			if (overlay.length > 0) {
				//move the last lightbox under the overlay
				var lb = $('.byb-lightbox:last').css('z-index',900);
				
				if ($.browser.msie === true && $.browser.version === '6.0') {
					lb.find('select').css('visibility','hidden');
				}																								
			}
			else {
				//create new overlay
				overlay = $('<div id="byb-overlay"/>').css('opacity',0);				
				$('body').append(overlay);
				overlay.animate({ opacity : 0.35 });				
			}		

			//IE6 requires hiding selects and manual resizing of overlay
			if ($.browser.msie === true && $.browser.version === '6.0') {
				$('#root select').css('visibility','hidden');
								
				$(window).resize(function(){
					$(overlay).height($(document).height());					
				}).triggerHandler('resize');
			}
			
			//we create the lightbox wrapper in a hidden state
			var wrapper = $('<div class="byb-lightbox"/>').hide();
			if (options.additionalClass) {
				wrapper.addClass(options.additionalClass);
			}
			if (options.id) {
				wrapper.attr('id',options.id);
			}
		
			var innerWrap = $('<div class="byb-wrapper"/>');
			wrapper.append(innerWrap);
			$('body').append(wrapper);	
			
			innerWrap.html(options.html);
			
			//that's the close button
			wrapper.find('.close a').click(function(e){
				e.preventDefault();
				Engine.utils.closeLightbox(wrapper);
			});								
			
			options.callback.apply(innerWrap);
			
			wrapper.fadeIn();
		},
		//close provided lightbox , can be used with #id
		closeLightbox : function(el) {
			el = $(el);
			
			el.fadeOut(function(){
				$(this).remove();
				
				//we check if there are any lightboxes underneath
				if ($('.byb-lightbox').length > 0) {
					//if so, we move it above the overlay
					var lb = $('.byb-lightbox:last').css('z-index','1100');
					if ($.browser.msie === true && $.browser.version === '6.0') {
						lb.find('select').css('visibility','visible');
					}																
				}
				else {
					$('#byb-overlay').fadeOut(function(){
						$(this).remove();
					});
					if ($.browser.msie === true && $.browser.version === '6.0') {
						$('#root select').css('visibility','visible');
					}											
				}
			});			
		}	
	},
	enhancements : {
		sliders : function(){
			$('.slider-a .slider-wrap').CNSlider({
				'display' : 4,
				'width' : 710
			});
			
			$('.slider-b .slider-wrap').CNSlider({
				'display' : 1,
				'width' : 692,
				'slider' : '.inner',
				'items' : '.inner ul'
			});		
			
			$('.slider-c .slider-wrap').CNSlider({
				'display' : 4,
				'width' : 410
			});	
			
		},
		configurator : function(){
			var options = $('.configurator .product-options');
			var btn = $('.configurator .submit');
			
			$('.slider-c .items a').click(function(e){
				e.preventDefault();
				$('.slider-c .items a').removeClass();
				$(this).addClass('active');
				var target = $(this).hrefId();
			    var productId = target.substring(target.lastIndexOf('~')+1,target.length);
			    target = $(target.substring(0,target.lastIndexOf('~')));
			    $.ajax({
			        url: "/byb/control/getProductVariants",
			        cache: false,
			        global: false,
			        type: "POST",
			        data: 'virtualProduct_id='+ productId,
			        dataType: "html",
			        success: function(msg){
					    	 options.show();
					    	 $('div#options-feature').html(msg);
							 btn.hide().show(); //hide show to fix IE no redraw bug
			        }
			    });
			});
		},
		comments : function(){
			$('.comments-a h2').click(function(){
				$(this).parent().toggleClass('comments-a-active');
			});
		},
		userSettings : function(){
			$('.user-settings h2').click(function(){
				$(this).toggleClass('active');
				$(this).next('.foldable').toggleClass('foldable-active');
			});
		},
		orderSummary : function(){

			//check if we are on the right page				
			if ( $('.checkout-form').length  === 0 ) {
				return;	
			}
			
			var summary = $('.checkout-form > .col-2'),
			    form = $('.checkout-form > .col-1');

			//check if summary is actualy longer than the form on the left side
			var diff = form.height() - summary.height();

			//order summary is actualy higher than details form (loads of items in cart)
			if (diff < 0) {
				return;
			}
			
			//check what the initial offset of summary is
			var baseOffset = summary.offset().top;
			
			var scrollIt = function(e){
				var offset = $(window).scrollTop() - baseOffset;	
				
				//offset cannot be negative
				if (offset < 0) {
					offset = 0;
				}
				
				//don't slide it too far
				if (offset > diff) {
					offset = diff;
				}
				
				summary.stop().animate({ 'marginTop' : offset });
			};
			
			$(window).scroll(scrollIt);
			
			//do the initial scrolling in case page is being refreshed
			scrollIt();
		},
		listing : function(){
			$('form.listing-options').each(function(){
				var 
					wrapper = $('<p class="options-a"/>'),
					selectNone,upload,selectAll, deleteSelected;

				var items = $(this).parent('.listing-a').find('.listing-items input[type=checkbox]');	
				var allMyImagesItems = $(this).parent('.allmyimages').find('.listing-items input[type=checkbox]');

				$(document).bind('listing.selectionChange',function(e){
					if($('.listing-items input[type=checkbox]:checked').length === 0) {
						selectNone.add(deleteSelected).addClass('disabled');
						return;
					}
					selectNone.add(deleteSelected).removeClass('disabled');
				});
				
				items.click(function(e){
					$(document).trigger('listing.selectionChange');
				});
				
				allMyImagesItems.click(function(e){
					$(document).trigger('listing.selectionChange');
				});
				
				upload = $('<a href="/byb/control/uploadImage" id="upload-trigger">Upload</a>').click(function(e){
					e.preventDefault();
					$.get($(this).attr('href'),function(data){
						Engine.utils.lightbox({
							'html' : data,
							'additionalClass' : 'byb-lightbox-b byb-lightbox-b-narrow'
						});						
					});
				});
				
				selectAll = $('<a href="#">Select all</a>').click(function(e){
					e.preventDefault();
					items.attr('checked','checked');		
					allMyImagesItems.attr('checked','checked');
					$(document).trigger('listing.selectionChange');
				});
				
				selectNone = $('<a href="#" class="disabled">Select none</a>').click(function(e){
					e.preventDefault();						
					if ($(this).hasClass('disabled')) {
						return;
					}
					items.attr('checked','');
					allMyImagesItems.attr('checked','');
					$(document).trigger('listing.selectionChange');					
				});

				deleteSelected = $('<a href="#" class="disabled">Delete selected</a>').click(function(e){
					e.preventDefault();						
					if ($(this).hasClass('disabled')) {
						return;
					}												
					$('form.listing-items').get(0).submit();						
				});
				
				$(document).triggerHandler('listing.selectionChange'); //we want to take possible page refresh with checked boxes into account
				if($('#upload-trigger').html()!=null){
					wrapper.append(upload,document.createTextNode(' | '))
				}
				wrapper.append(selectAll, document.createTextNode(' | '), selectNone, document.createTextNode(' | '), deleteSelected);

				$(this).prepend(wrapper);
			});			
		},
		forgotPassword : function(){
			$('a.forgot').click(function(e){
				e.preventDefault();
				
				Engine.utils.lightbox({
					'html' : $('#forgot-password-form').html(),
					'additionalClass' : 'byb-lightbox-a',
					'callback' : function(){ //this keyword relates always to lightbox wrapper in the callback function 
						$(this).find('label').compactize($(this).find('input'));
					}
				});
			});												
		},
		/*
		 * Displays a lightbox with edit options
		 */
		editDetails : function(){
			
			//this is only run on the listings page
			if ($('.listing-items').length === 0){
				return;
			}
			
			//fetch the edit details form and open it in a lightbox
			$('.listing-items .o .edit').click(function(e){
				e.preventDefault();
				$.get($(this).attr('href'),function(data){
					Engine.utils.lightbox({
						'html' : data,
						'additionalClass' : 'byb-lightbox-b'
					});						
				});				
			});
		},
	  imagesUpload : function(){
		$('#upload-trigger').click(function(e){
			e.preventDefault();
			$.get($(this).attr('href'),function(data){
				Engine.utils.lightbox({
					'html' : data,
					'additionalClass' : 'byb-lightbox-b byb-lightbox-b-narrow'
				});						
			});
		  });
		}
   },	
	fixes : {
		inputs : function(){
			if ($.browser.msie === false || $.browser.version !== '6.0') {
				return ;
			}
			$('input[type=text], input[type=password]').addClass('inputfield');
		}
	}
};
	
//functions initialized on document ready
jQuery(function($) {
	Engine.utils.links();
	Engine.utils.mails();
	Engine.utils.labels();

	Engine.enhancements.forgotPassword();
	Engine.enhancements.sliders();	
	Engine.enhancements.configurator();
	Engine.enhancements.comments();
	Engine.enhancements.userSettings();
	Engine.enhancements.orderSummary();

	Engine.enhancements.listing();

	//edit details popup
	Engine.enhancements.editDetails();
	
	//upload trigger
	Engine.enhancements.imagesUpload();
	
	Engine.fixes.inputs();
});


// Read and write cookies
// http://wiki.script.aculo.us/scriptaculous/show/Cookie
var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
}