/**
 * Some various js actions for Green Dragon and Pink Lotus sites.
 * 
 * @author		180byDesign
 * @url			http://www.180bydesign.com
 * @code		Michael Gilley <michael@180bydesign.com>
 * @package		default, Green Dragon Group site.
 * @copyright	2010. All rights reserved.
 */

// jQuery no conflict!
jQuery.noConflict();

// when document ready go!
jQuery(function() {
	GD.go();

});


// Global object Module pattern
// http://www.yuiblog.com/blog/2007/06/12/module-pattern/
var GD = (function($, undefined) {
	return {
		
		
		// Check to see if bootstrap file loaded:
		/* none of this works...
			if ( ! localConfig.siteURL) {
				var Config = {
					siteURL: {

						gdgroup: 	'http://gdgroup.loc/',
						gdstyle: 	'http://gdstyle.loc/',
						plclothing: 'http://yourmama1.loc/'

					}
				};
			
			} else {
				var plclothing = "yo";
				var Config = {
					siteURL: {

						gdgroup: 	localConfig.siteURL.gdgroup,
						gdstyle: 	localConfig.siteURL.gdgroup,
						plclothing: 'localConfig.siteURL.gdgroup;

					}
				};
			
			
			
		};	*/
		
		// walk thru all methods in init()
		go: function() {
			for (var i in GD.init) {
				GD.init[i]();
					
			}
		},
		
		init: {
			
			// do cool stuff with the menu
			menu: function() {
				if ($('.checkout-btn').length) {
					var ow = $('.quick-access .links li.last').outerWidth(),
						sw = $('.quick-access .checkout-btn').outerWidth(),
						comp = ow - sw + 9;
					
					$('.quick-access .checkout-btn').css('right', comp);
				}
			},
			// greendragon front page
			gdFront: function() {
				if ($('.cms-home.green').length) GD.getFront.green();
			},
			// pink lotus front page
			plFront: function() {
				if ($('.cms-home.pink').length) GD.getFront.pink();
			},
			// Featured Image Rollover Effects... this doesn't work for injected home pages 
			// but leaving it here for testing pages (
			// http://greendragongroupltd.com/main_pages/test_home_gd/ 
			// http://greendragongroupltd.com/main_pages/test_home_pl/ 
			featuredImages: function() {
				if ($('.gd_home').length) GD.getFrontRollovers.doit();
				if ($('.pl_home').length) GD.getFrontRollovers.doit();
			},
			
			// greendragon side banners
			gdBanners: function() {
				if ($('body.green').length) GD.getBanners.green();
			},
			// pink lotus front page
			plBanners: function() {
				if ($('body.pink').length) GD.getBanners.pink();
			},			
			allBanners: function() {
				if ($('.ml_left').length) GD.hideSignup.doit();
			},
			
			// switch color and sizes
			prodColorSwap: function() {
				if ($('.options-wrapper .row.size').length) GD.products.switchAttributes();
			},
			// handle product color options second
			prodColors: function() {
				if ($('.options-wrapper .row.color').length) GD.products.handleColors.init();
			},
			// handle product size options first
			prodSizes: function() {
				if ($('.options-wrapper .row.size').length) GD.products.handleSizes.init();
			},
			// product images rollover
			prodImages: function() {
				if ($('.product-img-box').length) GD.products.rollImages.init();
			},
			// Lookbook
			lookbook: function() {
				if ($('.lb_pink, .lb_green').length && ! $('.collection_list').length) GD.lookBook.init();
			}
		},
		
		hideSignup: {
			/* hide entire thing if they already filled it out */
			
			/*if ($.cookie('GD_Email_Signup').signedup) function() {
				
			};*/
			
			
			doit: function(){
				$(".ml_hide").hide();
				$(".ml_submit").hide();
				$("a.ml_title").click(function ( event ) {
					event.preventDefault();
				    $(this).hide();
					$(".ml_submit").show();  
					$(".ml_hide").show(50);
				    });
				$('#mce-EMAIL').clearingInput(); // Input value will be 'The label text'
				/* set cookie so that if they enter their info - they don't see advert again: */
				$(".mc-embedded-subscribe-form").submit(function ( event ) {
					$.cookie('GD_Email_Signup', 'signedup');
				});

				
			}
			
		},
		
		
		getFront: {
			green: function() {
				GD.getFront.inject(localConfig.siteURL.gdgroup +'green_dragon/');				
			},
			pink: function() {
				GD.getFront.inject(localConfig.siteURL.gdgroup +'pink_lotus/');
				
			},
			inject: function(url) {
				$.ajax({
					url: window.path + 'proxy.php?proxy_url='+url,
					success: function(data) {
						$('.col-main').append(data);
						// If successful, add rollover effects
						GD.getFrontRollovers.doit();
					}
				});
			}
		},
		
		getFrontRollovers: {
			/*
			getheight: function(){
				$(".img_rollover.row_1").height();
				/*$(".hm_feat_image").load(function() {
					(this).children(".img_rollover").height();
				});
			},
			*/
			
			doit: function (){
				/* first change height */
				 /*alert(GD.getFrontRollovers.getheight());
				 $(".hm_feat_image").hover(function() {
					$(this).children(".img_rollover").css({"height":(this).height()});
					});
				*/
				
				  $(".hm_feat_image").mouseenter(function() {
				    $(this).children(".img_rollover").fadeIn(150);
				  }).mouseleave(function() {
				     $(this).children(".img_rollover").fadeOut();
				  });
				
				
			}
			
		},
		
		
		getBanners: {
			green: function() {
				GD.getBanners.inject(localConfig.siteURL.gdgroup + 'sidebar_adverts/gd/');
			},
			pink: function() {
				GD.getBanners.inject(localConfig.siteURL.gdgroup + 'sidebar_adverts/pl/');
			},
			inject: function(url) {
				$.ajax({
					url: window.path + 'proxy.php?proxy_url='+url,
					success: function(data) {
						$('.block_callout_container').append(data);
						// If successful add signup effects
						GD.hideSignup.doit();
					}
				});
			}
			
				
			
		},
		
		products: {
			handleSizes: {
				init: function() {
					var $size = $('.options-wrapper .size select'),
						$boxes = $('<div class="boxes"/>');

					// insert the boxes in place of the select
					$size.before($boxes).css({
						position: 'absolute',
						left: -10000,
						top: -10000
					});
					
					this.loadOptions($size);
				},
				loadOptions: function($size) {
					var $size = $size || $('.options-wrapper .size select'),
						isDisabled = $size.attr('disabled'),
						$opts = $size.children('[value!=""]'),
						$boxes = (isDisabled) ? [] : $( GD.products.makeBoxes($opts) );
						
						
					// Insert Sizing Chart
					$('.size .dt').append($('.sizechart'));								
					// $('.size .dd .boxes').append($('.sizechart2'));
					//	$('.size .dd .sizechart2').removeClass('hide');
					$('.sizechart').tipsy({
						gravity: 'e',
						delayIn: 0,
						delayOut: 100, 
						fade: true,
						html: true,
						trigger: 'hover',
						live: false,
					 	opacity: 1.0, 
						/*title: function() {
							return $(this).find('span').text();
						}*/
						title: function(){
									return $('.sizechartimg').html();
								},  // attribute/callback containing tooltip text

						});
					$('.sizechart2').tipsy({
						gravity: 'n',
						delayIn: 0,
						delayOut: 100, 
						fade: true,
						html: true,
						trigger: 'hover',
						live: false,
					 	opacity: 1.0, 
						/*title: function() {
							return $(this).find('span').text();
						}*/
						title: function(){
									return $('.sizechartimg2').html();
								},  // attribute/callback containing tooltip text

						});
					
					
					
					
					if ($boxes.length) {
						// insert the boxes
						$size.prev().empty().append($boxes);
					
						// link the boxes with the select
						$boxes.click(function(e) {
							var $this = $(this),
								val = $this.attr('data-value'),
								$opt = $opts.filter('[value='+val+']');

							e.preventDefault();
							$this.parent().find('.selected').removeClass('selected').end().end().addClass('selected');
							$size.find('option:selected').removeAttr('selected');
							$opt[0].selected = "selected";

							// run prototype script for native control and update color swatches
							spConfig.configureElement($size[0]);

							// GD.products.handleColors.loadOptions();
							
							
							// Change TEXT to match selected size
							size =  $(this).find('span').text(); 
							$('div.options_desc .opt_two span').replaceWith(
								'<span>Size: <strong>' + size + '</strong>   </span>'
								);
								
							// Show that button is ready to GO!	
							
							$('div.add-btn button').addClass('ready');
												

							
						});
					} else {
						// there are no sizes available
						$size.prev().empty().append('<div class="size_desc"><span class="size_desc_arrow">&uarr;</span>Choose a Color</div>');
					}
				}
			},
			switchAttributes: function() {
				$('.row.size').before( $('.row.color') );
				// call prototype class!
				if (typeof spConfig == 'object') {
					spConfig = new Product.Config(spConfig);
				}
			},
			handleColors: {
				init: function() {
					var $select = $('.options-wrapper .color select'),
						$swatchWrapper = $('<div class="swatches" />');
					
					// hide away the select and prepare for takeover
					$select.css({
						position: 'absolute',
						top: -10000,
						left: -10000
					}).before($swatchWrapper);
					
					this.loadOptions($select);
				},
				loadOptions: function($select) {
					var $select = $select || $('.options-wrapper .color select'),
						isDisabled = $select.attr('disabled'),
						$opts = $select.children('[value!=""]'),
						$swatches = (isDisabled) ? [] : $(this.makeSwatches($opts));
				
					if ($swatches.length) {
						// $select.parents('.row').show();
						
						// insert the swatches
						$select.prev().empty().append($swatches);
		
						$swatches.click(function(e) {
							var $this = $(this),
								val = $this.attr('data-value'),
								
								$opt = $opts.filter('[value="'+val+'"]');
							
							e.preventDefault();
							
							
							
							$this.parent().find('.selected').tipsy('hide').data('tipsy', '').tipsy({
								gravity:'sw',
								title: function() {
									return $(this).find('span').text();
								}
							});
							
							$this.parent().find('.selected').removeClass('selected').end().end().addClass('selected');
							$select.find('option:selected').removeAttr('selected');
							$opt[0].selected = "selected";
							
							// Change TEXT to match selected name
							name =  $(this).find('span').text(); 
							$('div.options_desc .opt_one span').replaceWith(
								'<span><span class="selected_product_label">Selected</span>:&nbsp;&nbsp;  Color: <strong>' + name + '</strong>,&nbsp;&nbsp;</span>'
								);
							$('div.options_desc .opt_two span').replaceWith(
								'<span>Now choose a size.</span>'
								);	
						
							
							spConfig.configureElement($select[0]);
							
							GD.products.handleSizes.loadOptions();
							
							// stop tipsy and show!
							$this.unbind('mouseenter mouseleave').tipsy({trigger: 'manual'}).tipsy('show');
						}).tipsy({
							gravity: 'sw',
							title: function() {
								return $(this).find('span').text();
							}
						});
						
						$swatches.hover(function() {
							$(this).siblings('.selected').data('tipsy').$tip.hide();
						}, function() {
							$(this).siblings('.selected').data('tipsy').$tip.show();
						});
						
					} else {
						// there are no color options, so let's hide the row altogether
						// $select.parents('.row').hide();
					}
				},
				makeSwatches: function($opts) {
					var swatches = '';
					
					$opts.each(function(i) {
						var $this = $(this),
							matches = $this.text().match(/(.*)_#?([0-9A-Fa-f]{3,6})/),
							color = matches[2],
							colorName = matches[1],
							a = '';
						
						a += '<a href="#opt" class="radio index-'+i+'" style="background-color: #'+color+'" data-value="'+$this.val()+'">';
						a += '<span>' + colorName + '</span></a>';
						
						swatches += a;
					});
					
					return swatches;
				}
			},
			makeBoxes: function($opts) {
				var boxes = 'ddd';
				
				$opts.each(function(i) {
					var $this = $(this),
						a = '';
					
					a += '<a href="#opt" class="radio index-'+i+'" data-index="'+i+'" data-value="' + $this.val() + '">';
					a += '<span>' + $this.text() + '</span></a>';
						
					boxes += a;
				});
				
				return boxes;
			},
			selectMe: function() {
				// this refers to an instance of $
				if (! this.is('.selected')) {
					this.parents('ul:first').find('.selected').removeClass('selected');
					this.addClass('selected');
					$('#' + this.data('option')).click();
				}
				return false;
			},
			preSelect: function($context) {
				$context.find(':radio:checked').prev('a.radio').addClass('selected');
			},
			rollImages: {
				timer: null,
				$box: $('.product-img-box .product-image'),
				init: function() {
					var $box = $('.product-img-box .product-image'),
						$mvA = $('.more-views a');
					
					// if there is only one image do no hover effects
					if ($mvA.length <= 1) {
						$mvA.click(function() { return false; });
						return false;
					}
					
					$mvA.hover(function() {
						GD.products.rollImages.view(this, $box);
					}, function() {
						GD.products.rollImages.timer = setTimeout(GD.products.rollImages.reset, 500);
					}).click(function() { return false; });
				},
				view: function(el, $box) {
					var $el = $(el);
					clearTimeout(GD.products.rollImages.timer);
					$el.closest('ul').find('a.active, a.hover').removeClass('active hover');
					$el.addClass('hover');
					$box.find('img:visible').fadeOut(150);
					$box.find('.' + $el.attr('data-img')).fadeIn(150);
				},
				reset: function($box) {
					$('.product-img-box .product-image').find('img:visible').fadeOut(150);
					$('#image').fadeIn(150);
					$('.more-views a:first').addClass('active');
					$('.more-views a.hover').removeClass('hover');
				}
			}
		},
		
		lookBook: {
			timer: null,
			init: function() {
				// capture the nav images clicks and open
				$('.lb_right .col_nav a').click(function() {
					$(this).addClass('clicked');
					GD.lookBook.open(this);
					return false;
				}).hover(function() {
					GD.lookBook.view(this);
				}, function() {
					if (! $(this).is('.clicked')) {
						GD.lookBook.timer = setTimeout(GD.lookBook.reset, 500);
					}
				});
				
				$('.lb_right .arrow').click(function() {
					GD.lookBook.close();
				});
			},
			view: function(el) {
				clearTimeout(GD.lookBook.timer);
				$('.lb_left img:visible').fadeOut(150);
				$('.lb_left .'+$(el).attr('class')).fadeIn(150);
			},
			reset: function() {
				$('.lb_left img:visible').fadeOut(150);
				$('.lb_left .image_main').fadeIn(150);
			},
			open: function(el) {
				// open lookBook based on what id was passed
				var $this = $(el),
					ids = $.trim( $this.attr('class') ).match(/entry_([0-9]+)_([0-9]+)/i),
					eid = ids[1],
					rid = ids[2],
					$img = $('.col_info .entry_'+eid),
					$info = $('.col_info');
				
				if (! $img.length) return;
				
				$info.addClass('open');
				$info.find('.entry_'+eid).show();
				$info.animate({right: 0}, 350, 'easeOutExpo');
			},
			close: function() {
				$('.col_info').removeClass('open').animate({right: -450}, 350, 'easeOutExpo', function() {
					$('.clicked').removeClass('clicked');
					$(this).children('div:visible:not(.arrow)').hide();
					GD.lookBook.reset();
				});
			}
		}
	};
})(jQuery);
