$.fn.exists = function () {	
	return $(this).length;	
};

var kwiat = {
	
	global: {
		
		init: function() {
			this.tooltip();
			this.swap();
			this.mailing_list();
			this.send_to_friend();
			this.newsletter();
			this.datepicker();
			this.boutique_locator();
			this.drop_downs();
			kwiat.product_page.initialize_details_selection();
		},
		
		ie6_message: function() {
			
		},
		
		drop_downs: function() {
			if ( $.browser.msie ) {
				$('#navigation').find('li').hover(function() {
					$('> ul', this).show();
				}, function() {
					$('> ul', this).hide();
				});
			}
		},
		
		boutique_locator: function() {
			$('li.locate_boutique').find('a:first').click(function() {
				$('#locate_boutique').slideToggle();
				return false;
			});
			$('a.locate_close').click(function() {
				$('#locate_boutique').slideToggle();
				return false;
			});

			$('#locate').submit(function(){
				window.location = '/boutique-locator#zipcode=' + $('input#locate_text').val();
				return false;	
			});
		},
		
		datepicker: function() {
			$('input.datepicker').datepicker({
				changeMonth: true,
				changeYear: true,
				yearRange: '1920:2016'
			});
		},
		
		appt_datepicker: function() {
			$('input.datepicker').datepicker({
				changeMonth: true,
				changeYear: true,
				showOn: "both",
				buttonImage: "http://kwiatnew.optabc.com/images/date_icon.png",
				buttonImageOnly: true,
				yearRange: '1920:2016',
				minDate: 0
			});
		},
		
		newsletter: function() {
			
			$('li.email_signup').find('a:first').click(function() {
				$('#email_signup').slideToggle();
				return false;
			});
			
			$('a.email_close').click(function() {
				$('#email_signup').slideToggle();
				return false;
			});
			
			$('#Optin1').submit(function() {
				$.cookie( '_kwiat_signup_email', $('input[name="UEmail"]').val() );
			});
			
		},
		
		send_to_friend : function() {
			$('form[name=email2]').live('submit', function() {
				$.ajax({
					type: 'post',
					url: '/email.jsp',
					data: $('form[name=email2]').serialize(),
					success: function(msg) {
								alert('Your email has been sent.');
						$.fn.optPopup.close();
					}
				})
				return false;
			})
		},
		
		contact_concierge : function() {
			$('input#send').live('click', function() {
				$.ajax({
					type: 'post',
					url: '/contact.jsp',
					data: $('form[name=contactUs]').serialize(),
					success: function(msg) {
						$('form[name=contactUs]').find('h2').text('Email has been sent.');
					}
				})
				return false;
			})
		},
		
		swap : function() {
			
			$('a.swap').each(function() {
				
				var self = $(this),
						image = self.find('img'), 
						orig = image.attr('src'), 
						swap = image.attr('swap');
						
				self.hover(function() {
					image.attr('src', swap).css({
						border: '1px solid #EEE'
					});
				}, function() {
					image.attr('src', orig).css({
						border: '1px solid #fff'
					});
				});
				
				self.click(function() {
					image.attr('src', orig).css({
						border: '1px solid #fff'
					});
				})
				
			});
			
		},
		
		tooltip : function() {
			var tt_options = {
				position: {
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					},
					adjust: {
					  y: -2,
					  x: 0
					}
				},
				show: {
					solo: true,
					effect: {
						type: 'fade',
						length: 200
					}
				},
				hide: {
					fixed: true,
					effect: {
						type: 'fade',
						length: 300
					}
				},
				style: {
				  background: '#f5f5f5',
					border: {
						width: 1,
						radius: 1,
						color: '#ccc'
					},
					fontSize: '12px',
					width: {
						max: 300
					},
					tip: {
						corner: true,
						size: {
							x: 10,
							y: 6
						}
					}
				}
			};
			
			$('a.tooltip').each(function() {
				
				var self = $(this);
				
				if (self.find('img').width() > 200) {
					tt_options.position.adjust.y = 30;
				}
				/* IE fix for diabling alt attribute tooltip */
				if ( $.browser.msie ) {
						self.find('img').attr('alt', '');

				}
				self.qtip(tt_options);
			});
		},
		
		mailing_list: function() {

			// form input placeholders

			$('.place_holder').each(function() {

				var 
				self = $(this),
				// cache place holder
				temp = self.val();

				self.css('color', '#CECECE');

				self.focus(function() {
					if (self.val() === temp) {
						self.val('');
						self.css('color', '#222');
					}
				});

				self.blur(function() {
					if (self.val() === $.trim('')) {
						self.val(temp);
						self.css('color', '#CECECE');
					}
				});

			});

		}
		
	},
	
	home: function() {

		$('div.slides').cycle({
			fx: 'fade',
			timeout: 8000, 
			next: '.home_next',
			prev: '.home_prev',
			pause:   1 
		}).hover(function() {
			$('.home_prev, .home_next').show();
		}, function() {
			$('.home_prev, .home_next').hide();
		});
		//Click function to slides
		$(".home_slide").click(function(){
			var url=($(this).children('div').children('a').attr("href"));
			if($(this).children('div').length){
				window.location = url;
				return false;
			}
		}).hover(function(){
			if($(this).children('div').length){
				$(this).css('cursor','pointer');
			}
		},function(){
			$(this).css('cursor','default');
		});
	},

	bridal : {

		gallery : {

			initialize : function() {
				// kwiat.bridal.gallery.initialize_product_rotation();
				// kwiat.bridal.gallery.initialize_contact_concierge_popover();
				// this.sort_btn();
			},
			
			sort_btn : function() {
				var location = window.location.toString();
				if (location.indexOf('orderByPrice=ascPrice') !== -1) {
					$('#sort_asc').hide();
					$('#sort_desc').show();
				}
				else if (location.indexOf('orderByPrice=descPrice') !== -1) {
					$('#sort_desc').hide();
					$('#sort_asc').show();
				}
				else {
					$('#sort_asc').show();
					$('#sort_desc').hide();
				}
			},
			
			initialize_dropdown_menu : function() {
				$('div#navigation_container ul#navigation li').hover(function() {
					$(this).find('> ul').stop(true, true).fadeIn('fast');
				}, function() {
					$(this).find('> ul').stop(true, true).fadeOut('fast');
				});
			},
			
			initialize_product_rotation : function() {
				$('#product_images').cycle({
					fx: 'scrollHorz',
					speed: 700,
					timeout: 0,
					prev: 'a.prev_link',
					next: 'a.next_link',
					pager: '#pager'
				});
			},
			
			initialize_contact_concierge_popover : function() {
				
				$('a.contact_link').qtip({
					content: {
						text: $(container).find('div#contact_tooltip').html(),
						prerender: true
					},
					position: {
						corner: {
							target: 'bottomRight',
							tooltip: 'topRight'
						},
						adjust: {
						  y: 0,
						  x: -1
						}
					},
					show: {
						solo: true,
						effect: {
							type: 'fade',
							length: 200
						}
					},
					hide: {
						fixed: true,
						effect: {
							type: 'fade',
							length: 300
						}
					},
					style: {
					  background: '#f5f5f5',
						border: {
							width: 1,
							radius: 1,
							color: '#ccc'
						},
						width: {
							max: 400
						},
						tip: {
							corner: false,
							size: {
								x: 10,
								y: 6
							}
						}
					}
				}).click(function () {
					return false;
				});	
				
			}
			
		} // gallery
				
	}, // bridal

	product_page : {

		initialize : function() {
			kwiat.product_page.initialize_details_selection();
			kwiat.product_page.initialize_other_products_section();
			// kwiat.product_page.initialize_email_popup();
		},

		initialize_details_selection : function() {
			// Initialize the cycle plugin for the details section
			var $details = $('#details_cycle').cycle({
				fx:			'none',
				timeout:	0
			});

			// Allow the navigation links to go between details sections
			$('#details_nav a').each(function(i) {
		    var self = $(this);

			 	self.click(function() {
	        $details.cycle(i);
	        self.siblings().removeClass();
	        self .addClass('current');

	        return false;
			  });
			});
		},

		initialize_other_products_section : function() {
			
			var other_product = $('div#other_product'),
					other_products = $('#other_products');
			
			other_product.load($('a.others_ajax_url').attr('href'), function(data) {
			
				$('a.prev_link')[ $('a.previousButton').length > 0 ? 'show' : 'hide' ]();
				$('a.next_link')[ $('a.nextButton').length > 0 ? 'show' : 'hide' ]();
			
				kwiat.global.tooltip();
				kwiat.global.swap();
					
				$('a.temp_prev, a.temp_next').live('click', function() {

					var url = $(this).hasClass('temp_prev') ? $('a.previousButton').attr('href') : $('a.nextButton').attr('href');
					
					if ( typeof(url) !== 'undefined' ) {
						other_product.find('.product_cycle').fadeOut(function() {
							other_products.css('background','url("/images/kwiat_loader.gif") 363px 53px no-repeat');
							$.ajax({
								type: 'get',
								url: url,
								success: function(data) {
									other_products.css('background','none');
									other_product.html(data).fadeIn(function() {
										$('a.prev_link')[ $('a.previousButton').length > 0 ? 'fadeIn' : 'fadeOut' ]();
										$('a.next_link')[ $('a.nextButton').length > 0 ? 'fadeIn' : 'fadeOut' ]();
										kwiat.global.tooltip();
										kwiat.global.swap();
									});
								}
							});
						});
					}
					return false;
				});
				
			});
			
		},
		
		product_page_ajax : function() {
			
			var url = $('a.product_ajax_url').attr('href');
			
			$('select#metalValueId, select#colorValueId').live('change', function() {
					var mValue = $('select#metalValueId').attr('value');
					var cValue = $('select#colorValueId').attr('value');
					//url = url + "&propvalues=Metals@@"+mValue+";;Stone__Type@@"+cValue;
					//alert(mValue+" -- "+cValue +" URL : : "+url);
					
				$.ajax({
					type: 'get',
					//url: url+'&propvalues=Metals@@'+mValue+';;Stone__Type@@'+cValue,
					url: url+'&propvalues=Metals@@'+mValue+';;Color@@'+cValue,
					success: function(data) {
						if ($.trim(data).length > 0) {
							$('div.content').fadeOut(function() {
								$('div.content').html(data).fadeIn();
							});
						}
						else {
							alert("No Matching Product found");
						}
						Cufon.refresh();

					}
					
				});
				
				return false;
				
			});
			
		}
		
	},

	collections : {

		landing : {
			
			initialize : function() {
				// kwiat.collections.landing.intialize_collections_rotation();
				// kwiat.collections.landing.go_to_colection_from_address();
			},
			
			intialize_collections_rotation : function() {
				// Set a variable for the callback to know if it's the first time
				// going through it
				var first = true;

				$('#collections_cycle').cycle({
					fx: 'fade',
					prev: 'a.prev_link',
					next: 'a.next_link',
					speed: 700,
					timeout: 0,
					pager: '#pager',
					after: function(curr, next, opts) {
					  // Ignore this callback on page load; it interferes
					  // with the address initialization
	          if (first) {
	            first = false;
	            return;
	          }
						// Set the address hash to the id of the next slide
	          $.address.value($(next).attr('id'));
					}
				});
				
			},
			
			go_to_colection_from_address : function() {
				
				// Initialize function from the address plugin
				$.address.init(function(event) {
	        // Find the slide using the hash in the address
					// and remove the leading '/'
	        var $slide = $('div[id=' + event.value.substr(1) + ']');

	        // Find the slide's position in the cycle container
	        var position = $slide.prevAll().size();          

	        // Cycle to the specified slide
	        $('#collections_cycle').cycle(position);
	      });
	
			} // collection from addy
			
		}, // landing

		featured : {
			
			initialize : function() {
				kwiat.collections.featured.initialize_collection_rotation();
			},
			
			initialize_collection_rotation : function() {
				$('#collections_cycle').cycle({
					fx: 'fade',
					prev: 'a.prev_link',
					next: 'a.next_link',
					speed: 900,
					timeout: 0,
					pager: '#pager'
				});
			}
			
		} // featured
		
	}, // collections
	
	discover_kwiat : {
		
		our_ads : {
			
			init : function() {
				this.slide_show();
			},
			
			slide_show : function() {
				
				var ad_images = $('#ad_images').cycle({
					speed: 700,
					timeout: 0
				});
				
				$('#ad_list li').click(function() {
					
					ad_images.cycle( $(this).index() );
					
					return false;
				});
				
				$('div.related_prod').cycle({
					timeout: 0,
					prev: '.prev_set',
					next: '.next_set'
				});
					
			} // slide_show
			
		}, // our_ads
		
		red_carpet : {
			
			init : function() {
				this.swap_images();
				this.product_cycle();
			},
			
			product_cycle : function() {
				$('#products_container').cycle({
					timeout: 0,
					next: '.next_set',
					prev: '.prev_set'
				});
			},
		
			swap_images : function() {
				
				$('a.red_carpet_thumb').click(function() {
					
					$('a.prev_set, a.next_set').fadeOut();
					
					$.ajax({
						type: 'get',
						url: $(this).attr('href') + '?isAjax=true',
						success: function(data) {
							
							var html = $(data),
									p_image = html.find('img.individual_image').attr('src'),
		 							p_name = html.find('h2').text(),
									p_event = html.find('span.event_title').text(),
									p_products = html.find('div.linked_products').html(),
									p_products_len = html.find('div.linked_products').find('ul').length;
							
							$('img.current').attr({
								src: p_image
							}).load(function() {
								$('h3.name').text(p_name);
								$('h4.event').text(p_event);
								$('div#products_container').html(p_products);
								
								if ( html.find('div.linked_products').find('ul').length > 1 ) {
									$('a.prev_set, a.next_set').fadeIn();
								} else {
									$('a.prev_set, a.next_set').hide();
								}
								if (p_products_len <= 1) {
									$('#products_container ul').css({
										textAlign: 'left'
									});
								}
								kwiat.global.tooltip();
								kwiat.global.swap();
								kwiat.discover_kwiat.red_carpet.product_cycle();
							});
						}
						
					});
					
					return false;
					
				});
				
			} // swap_images
		
		} // red_carpet
		
	}, // discover_kwiat
	
	education : {

		facet: function() {
			$("#slide_facets #image_container li").hover(function() {
				var hoverIndex = $('#slide_facets #image_container li').index(this);
				$("#description_container #default_description").css('visibility', 'hidden');
				$('#slide_facets #description_container #description li').eq(hoverIndex).css('visibility', 'visible');
			}, function() {
				$('#slide_facets #description_container #description li').css('visibility', 'hidden');
				$("#description_container #default_description").css('visibility', 'visible');
			});
		},
		
		anatomy: function() {
			$("#slide_anatomy #image_container li").hover(function() {
				var hoverClass = $(this).attr('class');
				$('#slide_anatomy #description_container').css('visibility', 'visible');
				$('#slide_anatomy #description_container li.'+ hoverClass).css('visibility', 'visible');
			}, function() {
				$('#slide_anatomy #description_container').css('visibility', 'hidden');
				$('#slide_anatomy #description_container li').css('visibility', 'hidden');
			});
		},
		clarity :function() {
				$("#clarityscale_container #clarity_images_container img").mousemove(function (e) {
					var id = $(this).attr('id');
					var s_id = id.substring(0, id.length - 1);
					$("#description_container .description").css('visibility', 'hidden');
					$("#description_container #default").css('visibility', 'hidden');
					$("#description_container #" + s_id).css('visibility', 'visible');
				}).mouseout(function (e) {
					$("#clarityscale_container #description_container .description").css('visibility', 'hidden');
					$("#clarityscale_container #description_container #default").css('visibility', 'visible');
				});
		
		
		}
	}, // education
	 
	blog : {
	
		initialize : function() {
			//this.tabs();
		},
	
		tabs : function() {
			//$("ul.tabs").tabs("div.panes > div",{effect:'slide',speed:'slow'});
		}
		
	}, // blog
	
	results_grid: {
		
		init: function() {
			
			if ( $('#grid_wrapper').length > 0 ) {
				kwiat.results_grid.sorting();
				kwiat.results_grid.toggle_arrows();
				kwiat.results_grid.image_swap();
				kwiat.results_grid.pagination_ajax();
				$('#grid_wrapper').preloader();
			}
			
		}, // init

		sorting: function() {
			$('a.sort_by').click(function() {
				$('ul.sort_options').toggle();
				return false;
			});
		}, //sorting
		
		pagination_ajax: function() {
			
		 	var url, prod_list, page_list, page, current_page,
					hash = $.bbq, grid = $('#grid'),
					products = $('#grid_list'), 
					pagination = $('li.pagination');
			
			toggle_arrows = function() {
				$('.prev_link')[ $('#prev_grid').exists() ? 'fadeIn' : 'fadeOut' ]();
				$('.next_link')[ $('#next_grid').exists() ? 'fadeIn' : 'fadeOut' ]();
			},
			
			ajax_req = function( url, data ) {
				$.ajax({
					url: url,
					type: 'get',
					success: callback
				});
			},
			
			callback = function( data, status, jqHXR ) {
				if ( status === 'success' ) {
					prod_list = $(data).find('#grid_list').hide();
					page_list = $(data).find('li.pagination').contents().appendTo('<div></div>');
					products.fadeOut(function(event) {
						$('li.pagination').html( page_list );
						$('#grid').html( prod_list );
						$('#grid_wrapper').preloader();
						prod_list.fadeIn();
						toggle_arrows();
						kwiat.global.tooltip();
						kwiat.results_grid.image_swap();
					});
				}
			};
			
			$(window).bind( 'hashchange', function( event ) {
				page = hash.getState('page');
				url = url.replace(/&page=[0-9]+/gi, '&page=' + page );
				ajax_req(url);
			});
			
			$('div.pagination_wrapper').find('a').live('click', function() {
				if ( $(this).attr('href') !== '#' ) {	
					url = '/catalog.jsp?' + $(this).attr('href').split('?')[1] + '&view=productList';
					hash.pushState({ page: hash.getState('page') ? $(this).attr('href').match(/&page=[0-9]+/gi).toString().replace( '&page=', '') : 2 });
					if ( $(this).parent().parent().hasClass('sort_options') ) {
						$('ul.sort_options').toggle();
					}
				}
				return false;
			});
			
			$('a.prev_link, a.next_link').live('click', function() {
				if ( $(this).hasClass('prev_link') ) {
					$('#prev_grid').click();
				} else {
					$('#next_grid').click();
				}
				return false;
			});
			
			if ( window.location.hash !== '' && window.location.hash !== '#page=1' ) {
				url = $('#next_grid').attr('href');
				$(window).trigger('hashchange');
			}
			
		}, // pagination_ajax
		
		toggle_arrows: function() {
			$('.prev_link')[ $('#prev_grid').length > 0 ? 'fadeIn' : 'fadeOut' ]();
			$('.next_link')[ $('#next_grid').length > 0 ? 'fadeIn' : 'fadeOut' ]();
		}, // toggle_arrows
		
		image_swap: function() {
			$('ul#grid_list a').each(function() {
				var self = $(this),
						swap = self.attr('swap'),
						zoom_area = $('#zoom_area');
				self.hover(function() {
					zoom_area.attr('src', swap);
				}, function() {
					zoom_area.attr('src','/images/grid_crown.jpg');
				});
			});	
					
		} // image_swap
		
	}, // results_grid
	
	locator: function() {
		
		var hash = $.bbq,
				zipcode = hash.getState('zipcode'),
				locator = $('iframe#locator');
		
		if ( zipcode ) {
			locator.attr( 'src', 'http://hosted.where2getit.com/kwiat/?form=locator_search&search=Search&addressline=' + zipcode );
		}
		
	}
	
}

function validate(address) {
   var reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   if ( reg.test(address) == false ) {
      alert('Invalid Email Address');
      return false;
   }
}

$(function() {
	kwiat.global.init();
	kwiat.bridal.gallery.initialize_dropdown_menu();
	
	if ( $('ul.section_links') > 0 ) {
		$('ul.section_links').find('a[href="' + window.location.pathname + '"]').addClass('active');
	}
	
	$('form[name="contactUs"]').live('submit', function() {
		var data = $(this).serialize();
		$.ajax({
			type: 'post',
			url: '/contact.jsp',
			data: data,
			success: function(data) {
				alert('Your email has been sent.');
				$.fn.optPopup.close();
			}
		});
		return false;
	}).validate();
	$('form[name="contact_page"]').validate();
	
});
	
