/**
 * Master Scripts
 * Author: Motionlab Marketing Ltd.
 * www.motionlab.co.uk
 */

(function($) {

	
		
	/** ---------------------------------------
	 * IE6 PNG fixes
	 */
	
	if(typeof DD_belatedPNG !== 'undefined') {
		DD_belatedPNG.fix('img, .png_bg');
	}
	
	/** ---------------------------------------
	 * Bubbling
	 */
	  
	 $('[data-bubble="to"]').bind('click', function() {
 		var _anchor = $(this).find('[data-bubble="from"]').eq(0);
 		var _location = _anchor.attr('href') || '#';
 		window.location = _location;
 		return false;
 	});
 	
 	$('[data-bubble="from"]').click(function() {
 		/* $(this).closest('[data-bubble="to"]').trigger('click'); */
 		return false;
 	});
	
	/** ---------------------------------------
	 * Custom universal easing
	 */
	
	$.easing.custom = function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	};
	
	$.easing.easeInExpo = function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	};
	
	$.easing.easeOutExpo = function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	};
	
	/** ---------------------------------------
	 * IE6 upgrade message
	 */
	
	if(($.browser.msie && $.browser.version == '6.0')) {
		$('body').prepend("<div style='border: 1px solid #F7941D; background: #FEEFDA; text-align: center; clear: both; height: 75px; position: relative;'><div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'><a href='#' onclick='javascript:this.parentNode.parentNode.style.display=\"none\"; return false;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-cornerx.jpg' style='border: none;' alt='Close this notice'/></a></div>    <div style='width: 640px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'>      <div style='width: 75px; float: left;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-warning.jpg' alt='Warning!'/></div>      <div style='width: 275px; float: left; font-family: Arial, sans-serif;'>        <div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>You are using an outdated browser</div>        <div style='font-size: 12px; margin-top: 6px; line-height: 12px;'>For a better experience using this site, please upgrade to a modern web browser.</div>      </div>      <div style='width: 75px; float: left;'><a href='http://www.firefox.com' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-firefox.jpg' style='border: none;' alt='Get Firefox 3.5'/></a></div>      <div style='width: 75px; float: left;'><a href='http://www.browserforthebetter.com/download.html' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-ie8.jpg' style='border: none;' alt='Get Internet Explorer 8'/></a></div>      <div style='width: 73px; float: left;'><a href='http://www.apple.com/safari/download/' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-safari.jpg' style='border: none;' alt='Get Safari 4'/></a></div><div style='float: left;'><a href='http://www.google.com/chrome' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-chrome.jpg' style='border: none;' alt='Get Google Chrome'/></a></div></div></div>");
	}
	
	/** ---------------------------------------
	 * Reverse stacking
	 */

	$('.reverse-stack').each(function() {
		var childLength = $(this).children().length;
		$(this).children().each(function() {	
			$(this).css('zIndex', childLength);
			childLength--;
		});
	});
	
	/** ---------------------------------------
	 * Full height elements
	 */
	
	$('.full-height').each(function() {
		$(this).height($(this).parent().height());
	})
	
	/** ---------------------------------------
	 * Vertically centered elements
	 */
	
	$('.vertical-center').each(function() {
		var mid = $(this).children('.mid').eq(0);
		var val = ((mid.parent().height() - mid.height()) / 2);
		mid.css('top', val + 'px');
	});
	
	/** ---------------------------------------
	 * Horizontal masking (for carousels, tickers, etc.)
	 */
	
	$('.horz-mask').each(function() {
		var self = $(this);
		var height = self.height();
		var width = self.width();
		self.find('.horz-mask-inner > *').css('width', width);
	});
	
	/** ---------------------------------------
	 * Placeholder fallback
	 */
	
	if(!Modernizr.placeholder) {
		$('[placeholder]').focus(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
				input.removeClass('placeholder');
			}
			}).blur(function() {
			var input = $(this);
			if (input.val() == '' || input.val() == input.attr('placeholder')) {
				input.addClass('placeholder');
				input.val(input.attr('placeholder'));
			}
			}).blur().parents('form').submit(function() {
			$(this).find('[placeholder]').each(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
				}
			})
		});
	}
	
	/** ---------------------------------------
	 * Cycle
	 */
	 
	$('.cycle').each(function() {
		$(this).cycle({
			timeout: 8000
		});
	});
	
	
	/** ---------------------------------------
	 * Filter list
	 */
	 
	$('form.filter select').change(function(e) {
		$(this).closest('form').submit();
	});
	
	
	/** ---------------------------------------
	 * Homepage featured products
	 */
	
	if($('.spotlight').length) {
		
		var scrollableOptions = {
			touch: false,
			easing: 'easeOutExpo',
			duration: 600,
			items: '.horz-mask-inner'
		};
	
		if(Modernizr.touch) {
			scrollableOptions.touch = true;
		}
		
		$('.spotlight .horz-mask').scrollable(scrollableOptions);
		
		var spotlight = $('.spotlight .horz-mask').data('scrollable'),
			currentIndex = 0,
			disabled = false,
			nextSlide;
					
		$('.spotlight .pagination ol li a').click(function() {
			if($(this).hasClass('current')) return false;
			$('.spotlight .pagination ol li a').removeClass('current');
			$(this).addClass('current');
			var newIndex = $(this).parent().index();
			var currentItem = $('.spotlight ul li').eq(currentIndex);
			var newItem = $('.spotlight ul li').eq(newIndex);
			spotlight.seekTo(newIndex, 600);
			currentIndex = newIndex;
			clearInterval(nextSlide);
			nextSlide = setInterval(onNextSlide, 4000);
			return false;
		});
		
		var onNextSlide = function() {
			if(!disabled) {
				var nextAnchor = $('.spotlight .pagination li .current').parent('li').next('li').find('a');
				nextAnchor = (nextAnchor.length) ? nextAnchor : $('.spotlight .pagination li:first a');
				nextAnchor.trigger('click');
			}
		};
		
		$('.spotlight').hover(function() {
			disabled = true;
		}, function() {
			clearInterval(nextSlide);
			nextSlide = setInterval(onNextSlide, 4000);
			disabled = false;
		});
		
		
		
		nextSlide = setInterval(onNextSlide, 4000);
	
	}
	
	
	/** ---------------------------------------
	 * Hotspot images
	 */
	 
	 
	var resizeHotspots = function(e) {	
	
		
		var image = $(this).closest('li.palette').find('img.on');
		var scaleY = image.height() / image.data('height');
		var scaleX = image.width() / image.data('width');
		$(this).css({
			top:  $(this).data('top') * scaleY,
			left: $(this).data('left') * scaleX
		});	
	};
	
	$(window).load(function() {
	
		$('.hotspots li').each(function() {
			$(this).data('top', parseInt(this.style.top));
			$(this).data('left', parseInt(this.style.left));
			$(this).bind('resizeHotspots', resizeHotspots).trigger('resizeHotspots');
		});

		$(window).bind('resize', function() {
			$('.hotspots li').trigger('resizeHotspots');
		});
		
	});
	
	/** ---------------------------------------
	 * Fabrics
	 */
    $('#fabricsFormsList a').click(function() {
        
        href = $(this).attr('href');
        id = $(this).attr('id');
        
        $.ajax({
            type: "POST",
            url: href,
            success: function(msg){
                
                $('#wrap_' + id).remove();
                
                return false
            }
        });
        
        return false
        
    }); 
         
	
	var fabricList = $('.product-list.fabrics');
	if(fabricList.length) {			
		
		var changeHeights = function() {
			
			fabricList.find('li a img').each(function() {
				var imageRatio = $(this).outerHeight() / $(this).outerWidth();
				$(this).closest('li').css({
					height: $(this).outerHeight() + parseInt($(this).closest('a').css('marginTop')) + parseInt($(this).closest('a').css('marginBottom'))
				});
			});
		
		};
		
		$(window).bind('afterresize', changeHeights);
		$(window).load(function() {
			setTimeout(function() {
				changeHeights();
			}, 300);
		});
		
	}
	
	/** ---------------------------------------
	 * Fabrics
	 */
	
	var fabricsLi = $('.product-list.fabrics > ul > li');
	if(fabricsLi.length) {
		fabricsLi.hoverIntent({
			timeout: 400,
			over: function() {
				$(this).addClass('hover');
			},
			out: function() {
				$(this).removeClass('hover');
			}
		});
	}
	
	/** ---------------------------------------
	 * Fabric Basket
	 */
     
	fabricsLi.find('a').click(function(e) {
		e.preventDefault();
	});
	 
	var fabricBasket = $('#fabric-basket');
	
	/////
	//fabricBasket = null;
	////
	
	if(fabricBasket && fabricBasket.length) {
		var countHTML = fabricBasket.find('strong');
		var count = 0;
		var chosenFabrics = [];
		
		$('.chosen-fabrics > span').each(function() {
			chosenFabrics.push($(this).find('.remove').data('id'));
			count ++;
		});
        
        fabricBasket.find('.cancel').click(function(e) {
            count = 0;
            fabricBasket.removeClass('show');
            fabricsLi.removeClass('chosen');
            
            newSampleIds = null;
            $('#sampleIds').val(newSampleIds);
            
            $.ajax({
            type: "POST",
            url: '/fabrics/fabrics/setfabrics/' + newSampleIds,
            success: function(msg){
                }
            });
        });        
		
		fabricsLi.find('.request').click(function(e) {
			e.preventDefault();
			var li = $(this).closest('li');
			
			if(li.hasClass('chosen')) {
				return false;
			}
			
			li.addClass('chosen');
			count++;
			if(count != 0) {
				fabricBasket.addClass('show');
			}
			
			
			chosenFabrics.push(li.data('id'));

			$('.chosen-fabrics', fabricBasket).append('<span>' + li.find('h2').html() + ' <span data-id="' + li.data('id') + '" class="remove">X</span></span>');

			countHTML.html(count);
			var fabricPlural = (count==1) ? 'sample' : 'samples';
			fabricBasket.find('.pluralise').html(fabricPlural);
			
			if(count > 1) {
				fabricBasket.find('.mask').show().fadeOut(400);
			}
			
            /*
			fabricBasket.find('.cancel').click(function(e) {
				count = 0;
				fabricBasket.removeClass('show');
				fabricsLi.removeClass('chosen');
			});
            */
            
            oldSampleIds = $('#sampleIds').val();
            if(oldSampleIds == '')
                newSampleIds = oldSampleIds + chosenFabrics.join(','); 
            else {
                newSampleIds = chosenFabrics.join(',');
                
                
                if(oldSampleIds.indexOf(',' + li.data('id')) == -1 && oldSampleIds.indexOf(li.data('id') + ',') == -1){
                
                    newSampleIds = oldSampleIds + ',' + li.data('id');
                    
                }
                else
                    newSampleIds = oldSampleIds
                
            }
			
            //$('#sampleIds').val(chosenFabrics.join(','));
			$('#sampleIds').val(newSampleIds);
            
            $.ajax({
            type: "POST",
            //url: '/fabrics/fabrics/setfabrics/' + chosenFabrics.join(','),
            url: '/fabrics/fabrics/setfabrics/' + newSampleIds,
            //data: "name=John&location=Boston",
            success: function(msg){
                //alert(msg);
                }
            });
			
            //$('.chosen-fabrics > span').remove();
			
			
		});
		
	
		$('.chosen-fabrics .remove').live('click', function(e) {
            
			e.preventDefault();
            
			var id = $(this).data('id');
			var fabricTag = $(this).parent('span');


			$.each(chosenFabrics, function(i,v) {
                
				if(v == id) {
			
					
					chosenFabrics.splice(i,i);
					

					
					$('#sampleIds').val(chosenFabrics.join(','));
					count --;
					fabricTag.remove();
					if(count==0) {
						fabricBasket.removeClass('show');
						
					}
					
					fabricsLi.each(function() {
	
							if($(this).data('id') == id) {
								$(this).removeClass('chosen');
							}
						});
                    
                    oldSampleIds = $('#sampleIds').val();
                    
                    oldSampleIdsArr = oldSampleIds.split(',');
                    
                    //alert(oldSampleIds);
                    
                    newSampleIds = '';
                    
                    $.each(oldSampleIdsArr, function(index, value) { 
                      
                        if(value != id){
                            if(newSampleIds == '')
                                newSampleIds = value;
                            else
                                newSampleIds = newSampleIds + ',' + value;
                            
                        }
                        //alert(index + ': ' + value); 
                        
                        
                    });
                    
                    $('#sampleIds').val(newSampleIds);

                    
                    //alert(chosenFabrics);
                    //alert(chosenFabrics.join(','));
                    
                    // Then Remove From Session
                    $.ajax({
                        
                        type: "POST",
                        //url: '/fabrics/fabrics/setfabrics/' + chosenFabrics.join(','),
                        url: '/fabrics/fabrics/setfabrics/' + newSampleIds,
                        //data: "name=John&location=Boston",
                        success: function(msg){
                            //alert(msg);
                            }
                        });                    
                    
					return false;
				}
			});
			
			
			
		});
	
	}
	
	/*
	var fabricList = $('.product-list.fabrics');
	if(fabricList.length) {
				
		fabricList.find('li a').each(function() {
			
			$(this).data('props', {
				left: parseInt($(this).css('marginLeft')),
				top: parseInt($(this).css('marginTop')),
				width: $(this).outerWidth(),
				height: $(this).outerHeight()
			});
			
			$(this).bind('mouseenter', function() {
					
					var self = $(this);
					var props = self.closest('li').find('a').data('props');
			

					fabricList.find('.largeFabric').each(function() {
						
						if($(this).hasClass('hover')) {
						
						var other = $(this);	
						var otherProps = other.closest('a').data('props');
						other.closest('li').removeClass('hover');
											
						
						self.animate({
							width: otherProps.width,
							height: otherProps.height,
							left: otherProps.left,
							top: otherProps
						}, {
							duration: 100,
							complete: function() {
								
							}
						});
			
			

						
						setTimeout(function() {
						//other.stop().fadeOut(200);
						other.hide();
						}, 200);
						
						}
						
					});

					
					var largeFabric = self.parent('li').find('.largeFabric');
					
					largeFabric.closest('li').addClass('hover');
					
					//if(largeFabric.is(':animated')) return false;
					
					largeFabric.show();
					
					
					
					largeFabric.css(props);
					
			
					if(!largeFabric.find('img').length) {
						largeFabric.append('<img src="' + self.find('img').data('largesrc') + '" />');
					}
					else {
						largeFabric.find('img').attr('src', self.find('img').data('largesrc'));
					}
				
					
					
largeFabric.animate({
						width: largeFabric.width() * 1.5,
						height: largeFabric.height() * 1.5,
						left: largeFabric.position().left - ((largeFabric.width()) / 4),
						top: largeFabric.position().top - ((largeFabric.height()) / 3.5)
					}, {
						duration: 100,
						easing: 'easeOutExpo',
						complete: function() {
						
						}
					});


					
				});
		
			
		});
		
		
		fabricList.find('li .largeFabric').bind('mouseleave', function() {
								
			var self = $(this);	
			
			
			
			var props = self.closest('li').find('a').data('props');
			
			self.closest('li').removeClass('hover');


			self.css({
				width: props.width,
				height: props.height,
				left: props.left,
				top: props.top
			});
			
			//setTimeout(function() {
			self.stop().fadeOut(200);
			//}, 200);
			
		});
		
	}
	*/
	
	/** ---------------------------------------
	 * Sub menu
	 */
	 
	$('#side-nav ul ul ul').parent('li').hoverIntent({
		over: function() {
			$(this).children('ul').addClass('show');
		},
		out: function() {
			
		}
	});
	
	$('#side-nav').mouseout(function() {
		$(this).find('ul ul ul').removeClass('show');
	});
	
	$('#categories').prev('a').click(function(e) {
		e.preventDefault();
	});
	
	$('#side-nav ul ul ul').hoverIntent({
		over: function() {
		
		},
		out: function() {
			$(this).removeClass('show');
		}
	});
	
	
	
	/** ---------------------------------------
	 * Form elements
	 */
	 
	$('.intro .filter select').uniform();
	
	/** ---------------------------------------
	 * Product filters
	 */
	 
	$('.intro .filter select').each(function() {
		var selected = false;
		var val;
		var title;
		var self = $(this);
		$(this).find('option').each(function(i) {
			
			
			if($(this).attr('selected') && i) {
				selected = true;
				val = $(this).text();
				title = self.data('title');
				return false;
			}
			
		});
		if(selected && val) {
				$(this).parent('.selector').append(
				'<div class="selected">'
				+ '<strong>' + title + '</strong>' + ': '
				+ val
				+ '<strong class="close" id="close-' + title + '">X</strong>'
				+ '</div>');
			}
            
            $('#close-Style').click(function() {
                $('#styleselect').val('None');
                $('form.filter').submit();
            });
            
            $('#close-Material').click(function() {
                $('#materialselect').val('None');
                $('form.filter').submit();
            });            
            
            
            
	});
	
	$('.selector .selected .close').live('click', function() {
		var title = $(this).closest('.selector').find('select').attr('data-title');
		console.log(title);
		var form = $('form[name="' + title + '"]');
		console.log(form);
		form.submit();
	});
	
	/** ---------------------------------------
	 * Google Map
	 */
	
	if($('#map').length) {
	
		if (GBrowserIsCompatible()) {
		
			var map = new GMap2(document.getElementById("map"));
			var centre;
			if($('#map').data('lat')) {
			centre = new GLatLng($('#map').data('lat'),$('#map').data('lng'));
			map.setCenter(centre, 13);
			} else {
			centre = new GLatLng(53.67846,-1.70785);
			map.setCenter(centre, 6);
			}
			
			map.addControl(new GSmallZoomControl3D());
			
			function addMarker(self, lat, lng) {
				
				var itemCentre = new GLatLng(lat, lng);
				var blueIcon = new GIcon(G_DEFAULT_ICON);
				blueIcon.image = "/img/marker.gif";
				markerOptions = { icon:blueIcon };
				var globalMarker = new GMarker(itemCentre, markerOptions);
				map.addOverlay(globalMarker);
				
				if(self !== null) {
					GEvent.addListener(globalMarker, "click", function() { location.href = self.attr('href'); });
				}
			
			}
			
			if($('.showroom-list li a').length) {
				$('.showroom-list li a').each(function() {
					addMarker($(this), $(this).data('lat'), $(this).data('lng'));
				}); 
			}
			else if($('#map').data('lat')) {
				addMarker(null, $('#map').data('lat'), $('#map').data('lng'));
			}
			
		}
		
		
	}
    
    /** ---------------------------------------
     * dl pl slideout
     */
    $('.dl-pl h2').click(function(){
               $(this).next('.form').slideToggle('fast');
               $(this).toggleClass('open')
               return false;
    });    


})(this.jQuery);

