

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html

 *

 */



/**

 * Create a cookie with the given name and value and other optional parameters.

 *

 * @example $.cookie('the_cookie', 'the_value');

 * @desc Set the value of a cookie.

 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });

 * @desc Create a cookie with all available options.

 * @example $.cookie('the_cookie', 'the_value');

 * @desc Create a session cookie.

 * @example $.cookie('the_cookie', null);

 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain

 *       used when the cookie was set.

 *

 * @param String name The name of the cookie.

 * @param String value The value of the cookie.

 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.

 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.

 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.

 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained

 *                             when the the browser exits.

 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).

 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).

 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will

 *                        require a secure protocol (like HTTPS).

 * @type undefined

 *

 * @name $.cookie

 * @cat Plugins/Cookie

 * @author Klaus Hartl/klaus.hartl@stilbuero.de

 */



/**

 * Get the value of a cookie with the given name.

 *

 * @example $.cookie('the_cookie');

 * @desc Get the value of a cookie.

 *

 * @param String name The name of the cookie.

 * @return The value of the cookie.

 * @type String

 *

 * @name $.cookie

 * @cat Plugins/Cookie

 * @author Klaus Hartl/klaus.hartl@stilbuero.de

 */

jQuery.cookie = function (name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

(function ($) {
	$.fn.equalHeight = function () {
		var minimum = arguments[0] || 0;
		this.each(function () {
			if ($(this).height() > minimum) {
				minimum = $(this).height();
			}
		});
		$(this).css("min-height", minimum + 'px');
		if ($.browser.msie) {
			$(this).height(minimum).css('overflow', 'hidden');
		}
	}
})(jQuery);

/**
 * SimpleFlame Content rotator
 * Version 0.2 (28.04.2009)
 * Possible effects to use :
 *  - if UI effects have been added: 'blind', 'bounce', 'clip', 'drop', 'explode', 'fold', 'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide', 'transfer'
 *  - basic effects from jQuery: fadeIn, fadeOut, show, hide, slideUp, slideDown
 */
(function () {
	var sfRotator = function (el, options) {
			this.settings = {
				'item': 'li',
				'activeClass': 'active',
				'duration': 5000,
				'autorotate': true,
				'effectIn': 'fadeIn',
				'optionsIn': {},
				'speedIn': 'normal',
				'effectOut': 'fadeOut',
				'optionsOut': {},
				'speedOut': 'normal',
				'pauseOnHover': true
			};
			jQuery.extend(this.settings, options);
			this.$container = jQuery(el);
			this.build();
		};
	sfRotator.prototype.build = function () {
		this.$container.addClass('sf-items');
		this.$wrapper = jQuery('<div class="sf-rotator" />');
		this.$container.before(this.$wrapper);
		this.$wrapper.append(this.$container);
		this.$controls = jQuery('<ul class="sf-controls" />');
		this.$wrapper.append(this.$controls);
		this.$items = this.$container.children(this.settings.item);
		this.$current = this.$items.index(this.$items.filter('.' + this.settings.activeClass));
		if (this.$current < 0) {
			this.$current = 0;
		}
		var self = this;
		this.$items.addClass('sf-item').each(function (index, item) {
			var trigger = jQuery('<li><a href="#">' + parseInt(index + 1, 10) + '</a></li>');
			self.$controls.append(trigger);
			trigger.find('a').data('item', item).bind('click', {
				self: self
			}, self.trigger);
		});
		this.activate(this.$current, true);
		if (this.settings.autorotate) {
			this.autorotate();
		}
	};
	sfRotator.prototype.trigger = function (event) {
		event.preventDefault();
		var self = event.data.self;
		self.stopAutorotate();
		self.$rotationTerminated = true;
		var position = self.$items.index(jQuery(this).data('item'));
		self.activate(position);
	};
	sfRotator.prototype.activate = function (position) {
		var instant = arguments[1] || false;
		var activeClass = this.settings.activeClass;
		var oldItem = this.$items.eq(this.$current);
		var newItem = this.$items.eq(position);
		var onHide = function () {
				oldItem.removeClass(activeClass);
			};
		var onShow = function () {
				newItem.addClass(activeClass).css('zIndex', 10);
			};
		var effects = ['blind', 'bounce', 'clip', 'drop', 'explode', 'fold', 'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide', 'transfer'];
		if (instant === true) {
			oldItem.removeClass(activeClass).hide();
			newItem.addClass(activeClass).show();
		} else {
			if (jQuery.inArray(this.settings.effectOut, effects) > -1) {
				oldItem.hide(this.settings.effectOut, this.settings.optionsOut, this.settings.speedOut, onHide);
			} else if (jQuery.isFunction(oldItem[this.settings.effectOut])) {
				oldItem[this.settings.effectOut](this.settings.speedOut, onHide);
			} else {
				throw "Unsupported hide transition";
			}
			newItem.css('zIndex', 100);
			if (jQuery.inArray(this.settings.effectIn, effects) > -1) {
				newItem.show(this.settings.effectIn, this.settings.optionsIn, this.settings.speedIn, onShow);
			} else if (jQuery.isFunction(newItem[this.settings.effectIn])) {
				newItem[this.settings.effectIn](this.settings.speedIn, onShow);
			} else {
				throw "Unsupported show transition";
			}
		}
		this.$controls.find('a').removeClass('active').eq(position).addClass('active');
		this.$current = position;
	};
	sfRotator.prototype.autorotate = function () {
		this.$rotationTerminated = false;
		var self = this;
		this.$container.mouseenter(function () {
			if(self.settings.pauseOnHover == true){
				self.stopAutorotate();
			}
		});
		this.$container.mouseleave(function () {
			if(self.settings.pauseOnHover == true){
				self.startAutorotate();
			}
		});
		this.startAutorotate();
	};
	sfRotator.prototype.startAutorotate = function () {
		if (this.$rotationTerminated === true) {
			return;
		}
		var self = this;
		this.$rotationInterval = window.setInterval(function () {
			var next = self.$current + 1;
			if (next === self.$items.length) {
				next = 0;
			}
			self.activate(next);
		}, this.settings.duration);
	};
	sfRotator.prototype.stopAutorotate = function () {
		if (this.settings.autorotate) {
			window.clearInterval(this.$rotationInterval);
		}
	};
	jQuery.fn.sfRotator = function (options) {
		options = options || {};
		return this.each(function () {
			var r = new sfRotator(this, options);
		});
	};
})();
/**
 * Compact labels plugin
 * Takes one option
 *  - labelOpacity [default: true] - set to false to disable label opacity change on empty input focus
 */
(function($){$.fn.compactize=function(options){var defaults={labelOpacity:true};options=$.extend(defaults,options);return this.each(function(){var label=$(this),input=$('#'+label.attr('for'));input.focus(function(){if(options.labelOpacity){if(input.val()===''){label.css('opacity','0.5');}} else{label.hide();}});if(options.labelOpacity){input.keydown(function(){label.hide();label.css('opacity',1);});} input.blur(function(){if(input.val()===''){label.show();} if(options.labelOpacity){label.css('opacity',1);}});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
 *
 */
jQuery(function($) {
 
	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(){
				$('form.newsletter-a label, form.search label').compactize();
			}
		},
		ui : {
			featured : function(){
				$('#featured').sfRotator({
					item : 'div.item',
					duration: 4000,
					pauseOnHover: false
				});
			}			
		},
		fixes : {
			tableRows : function(){
				if (!$.browser.msie || $.browser.version !== '6.0') {
					return;
				}
				
				$('table tbody tr:first-child').addClass('first');
			}
		},
		
		tweaks : {
			
			ecom : function(){
				
				$("p.catImg").html($("span.catalogImage").html()); // render cat image
				
				if($("li.catalogueItemNotFound").html() == "This catalog has no sub-catalogs."){
					$("div.products-a").hide(); // hide the cats if none
				}
				
				
				if($("div.products-b li.productItemNotFound").html() == "This catalog has no products."){
					$("div.products-b").hide(); // hide the cats if none
				}
				
				
				// add to cart button tweak
				$(".productWrap").each(function(){

					//$(this).find("input.productSubmitInput").val("ADD TO BASKET");
					//$(this).find("input.productSubmitInput").css("width","120px").css("height","23px");
					
				});
				
				
				// make 1 col for product detail
				// if(productDetailRewrite == true){
				if(typeof(productDetailRewrite) !== 'undefined') {
						$("div.products-a").hide();
						$("div.cols-c").attr("class","cols-c cols-c-large");
						$("li.productItem").addClass("largeProduct");
						if($("div.catProdAttributeItem").html() == ""){
							$("div.catProdAttributeTitle").hide();
						}
						$("div#content").show();
					}
				
				// for list view. if no grouping then hide label
				if(typeof(productDetailRewrite) === 'undefined') {
						$("div#content").show();
				}
				
				
				// yank bottom border from you also might like prod
				$("div.recommended td.productItem:last").css("border-bottom","0px");
				
				// add poplets class to poplets table
				$("table.productPoplets").addClass("poplets");
				
				//$("input.productSubmitInput").css("width","120px").css("height","23px");
				//$("input.productSubmitInput").val("ADD TO BASKET");
					
				// kill useless cat li
				$(".catalogueList li.catalogueItem, .catalogueList li.catalogueItemLast").remove();
					
				
				
			
			}, // ecom
			
			equalize : function(){
               $('ul.productList li').equalHeight();
               $('ul.catalogueList li').equalHeight();
                                
            },
			
			loginPeepShow : function(){
			
				$("#btnLostPass").click(function(){
					$("#lostPass").slideToggle();
					return false;
				});
			
				
				$("#btnRegister").click(function(){
					$("#registerForm").slideToggle();
					return false;
				});
			
			
			},
			
			checkout : function(){
				// -----------------------------------------------------
				// This will copy over the shipping address value to the 
				// billing address.  Make sure the checkbox Id is "SameAsShipping"
				//
				// * Update - changed to check length and clear fields on unchecked
				// -----------------------------------------------------	

		},// end checkout
		
		events : function(){
			$(".col-b div.items:first").css("background","none");
			
			
			$("div.webappOutput div.items").each(function(){
				if($(this).find(".col4-data a").attr("href") == ""){
					$(this).find(".col4-data a").hide();
				}
			});
			
			if($("div.event-single a.button-a").attr("href") == ""){
				$("a.button-a").hide();
			}
			
			if($("li#addtogoogle a").attr("href") == ""){
				$("li#addtogoogle").hide();
			}
			
			if($("li#addtooutlook a").attr("href") == ""){
				$("li#addtooutlook").hide();
			}
			
			if($("li#addtoical a").attr("href") == ""){
				$("li#addtoical").hide();
			}
			
			if($("li#addtoyahoo a").attr("href") == ""){
				$("li#addtoyahoo").hide();
			}
			
			if($("li#addtogoogle a").attr("href") == "" && $("li#addtooutlook a").attr("href") == "" && $("li#addtoical a").attr("href") == "" && $("li#addtoyahoo a").attr("href") == ""){
				$("h5.addtoheading").hide();
				
			}
			
			$(".col4-data").each(function(){
				var href = $(this).find("a").attr("href");
				if(!href){
					$(this).css("display","none");
				}
			});
		},// events
		
		productAttributeAddon : function(){
			// for product detail.  Hide label if attributes instead of grouping
			if(typeof(productDetailRewrite) !== 'undefined') {
				if($("div.catProdAttributeItem select").length > 0 || $("div.catProdAttributeItem select").length == 0){
					$("div.catProdAttributeTitle:first").hide();
					$("div.catProdAttributeTitle:nth-child(2)").hide();
				}
			} 
				
			// for list view. if no grouping then hide label
			if(typeof(productDetailRewrite) === 'undefined') {
				$("div.attributes").each(function(){
				
					   var html =  $(this).find("div.catProdAttributeItem").html()
						if(!html){
							$(this).find("div.catProdAttributeTitle").hide();
						}
				
				});
			}
				
				
			}, // productAttributeAddon
			
			blogTweak : function(){
				if(window.location.href.indexOf("/Link_Lists/") != -1){
					$("div.recentCatsHide, .post-a .post-discussion, .blog-a .aside .search").hide();
					$("div.post-a").css("background","none");
				}
			},// blogTweak
			
			hideRelated : function(){
				// for product detail.  Hide label if attributes instead of grouping
				if(typeof(productDetailRewrite) !== 'undefined') {
					if(jQuery("span.relatedProdContainer div").length <= 1){
						jQuery("div.recommended").hide();
					}	
				}
			},
			
			
			toursApp : function(){
				
				// LIST VIEW
				$("li.tourItem").each(function(){
													
				list = "";
				
				// DYNAMIC DROPS FOR LISTING PAGES
				$(this).find("div.tourData").each(function(){

						var bookingId = $(this).find("span.tour-booking-id").text();
						var date = $(this).find("span.tour-tour-date").text();
						var cost = $(this).find("span.tour-cost").text();
						
					
						list += "<option value='"+bookingId+"' class='"+cost+"'>"+date+" $"+cost+"</option>";
					});
					
					$(this).find("select.toursDrop").append(list);
					
					if($(this).find("div.toursList").text() == "No items found."){
						
						$(this).find("select.toursDrop option.hide").removeClass("hide").text("No Dates");
						$(this).find("p.buyNow, div.qty").hide();
						$(this).find("div.productAttributes").html("<p style='color:red;'>No Dates Available</p>");
						
						}else{
					
						$(this).find("select.toursDrop option.hide").remove();
					
					}
				
				});
				
				
				// COOKIES FOR LIST PAGE
				if($("li.tourItem").length >= 0){ // we must be on the tours page reset cookies and run script
				
				$.cookie('tourCost',null);
				$.cookie('tourHowMany',null);
				
				//console.log($.cookie('tourCost'));
				//console.log($.cookie('tourHowMany'));
				
					//$("li.tourItem input.tourSubmit").each(function(){
		
						$("li.tourItem input.tourSubmit").click(function(){
																		
							var tourCost = $(this).closest('.options').find('select.toursDrop option:selected').attr("class");
							var tourHowMany = $(this).closest('.options').find('input.productTextInput').val();

							//alert($(this).closest('.options').find('select.toursDrop option:selected').attr("class"));
							
							//var tourCost = $(this).find("select.toursDrop option:selected").attr("class");
							//var tourHowMany = $(this).find("input.productTextInput").val();
							if(tourHowMany == 0 || tourHowMany == ""){
								alert("Please choose a non-zero value for quantity");
								return false;
							}else{
								$.cookie('tourCost',null);
								$.cookie('tourHowMany',null);
								
								$.cookie('tourCost',tourCost); // tour cost grabbed from class of select.. i know weird.
								$.cookie('tourHowMany',tourHowMany);
								//alert ($.cookie);
								return;
							}
												   
							
							//console.log(tourCost);
							//console.log(tourHowMany);
							
							//console.log($(this).parents('div.options').find("select.toursDrop option:selected"));
							
							//return false;
							return;
							
						
						});
					//});
					
				}// end if
				
				
				
				// DYNAMIC DROP FOR DETAILS PAGES
				if(jQuery("ul.productLarge").length > 0){
					
					jQuery("div.tourData").each(function(){
	
						var bookingId = jQuery(this).find("span.tour-booking-id").text();
						var date = jQuery(this).find("span.tour-tour-date").text();
						var cost = jQuery(this).find("span.tour-cost").text();
						
						
						jQuery("select.toursDrop").append("<option value='"+bookingId+"' class='"+cost+"'>"+date+" $"+cost+"</option>");
					});
					
					jQuery("select.toursDrop option.hide").remove();
					
					
					
					// COOKIE SET FOR DETAIL PAGE
					$("p.buyNow input.tourSubmit").click(function(){
						var tourCost = $("select.toursDrop option:selected").attr("class");
						var tourHowMany = $("input.productTextInput").val();
						
						if(tourHowMany == 0 || tourHowMany == ""){
							alert("Please choose a non-zero value for quantity");
							return false;
						}else{
							$.cookie('tourCost',null);
							$.cookie('tourHowMany',null);
							
							$.cookie('tourCost',tourCost); // tour cost grabbed from class of select.. i know weird.
							$.cookie('tourHowMany',tourHowMany);
							return;
						}											
					});
					
				
				}// END IF
				
				// for tours page.. hide if no tours
				jQuery("li.tourItem").each(function(){
					if(jQuery(this).find("div.productAttributes p:first").text() == "No Dates Available"){
						jQuery(this).hide();
					}
				
				});
			
			
			}, // eventsApp
			
			hideDateBlog : function(){
				// hide the date on the fake blog posts
				if(window.location.href.indexOf("/_blog/Link_Lists/") != -1){
					$("p.meta").hide();	
				}
			},
			
			newsletterInputClear : function(){
			
				jQuery("form.newsletter-a input").focus(function(){
                        var text = jQuery(this).val();
                        jQuery(this).val("");
                        jQuery(this).blur(function(){
                             if(text == jQuery(this).val() || jQuery(this).val() == ""){
                                  jQuery(this).val(text);
                             }
                        });
                   });
			
			},
			
			sendAsGift : function(){
				/*
				if(jQuery("ul.productSmall").length > 0){
					jQuery("li.productItem, li.productItemLast").each(function(){
					   jQuery(this).find("a.giftLink").attr("href",jQuery(this).find("p.productLink a").attr("href"));
					});
				}
				*/
				
				if(jQuery("div.recommended").length > 0){
					jQuery("td.productItem").each(function(){
					   jQuery(this).find("a.giftLink").attr("href",jQuery(this).find("p.productLink a").attr("href"));
					});
				}
	
			} // sendAsGift


			
		}// tweaks
	};

	Engine.utils.links();
	Engine.utils.mails();
	Engine.utils.labels();
	
	Engine.ui.featured();
	
	Engine.fixes.tableRows();
	
	Engine.tweaks.ecom();
	Engine.tweaks.equalize();
	Engine.tweaks.loginPeepShow();
	Engine.tweaks.checkout();
	Engine.tweaks.events();
	
	Engine.tweaks.productAttributeAddon();
	
	Engine.tweaks.blogTweak();
	//Engine.tweaks.hideRelated();
	
	Engine.tweaks.toursApp();
	Engine.tweaks.hideDateBlog();
	Engine.tweaks.newsletterInputClear();
	Engine.tweaks.sendAsGift();
	

	if($.cookie("wholesaleLoggedIn") == "true"){
		$("p.copyright a:first").text("Wholesale Page");
		$("p.copyright a:first").attr("href", "/wholesale/");
		 
	}
	
	function address2(){
		$("#BillingAddress").val($("#BillingAddress").val()+" "+$("#BillingAddress2").val());
		$("#ShippingAddress").val($("#ShippingAddress").val()+" "+$("#ShippingAddress2").val());
	}
	
});
