/*Super Global Variables*/
var cflag = 0,
    soopen = false,
	uid = '',
	login1val = {
		rules: {
			email_lf1: {
				required:true,
				email:true
			}
		},
		errorElement: 'span',
		submitHandler: function(){
				login.checkUserExists('standard');
			}
	},
	regform1 = {
		rules: {
			'regdata[email]': {
				required:true,
				email:true
			},
			'regdata[password]':{
				required:true
			},
			'regdata[password_conf]':{
				required:true,
				equalTo: '#pw'
			},
			'regdata[firstname]':{
				required:function(){
					if($('#q4:checked').length>0) {
						return true;
					} else {
						return false;
					}
				}
			},
			'regdata[lastname]':{
				required:function(){
					if($('#q4:checked').length>0) {
						return true;
					} else {
						return false;
					}
				}
			},
			'regdata[address1]':{
				required:function(){
					if($('#q4:checked').length>0) {
						return true;
					} else {
						return false;
					}
				}
			},
			'regdata[city]':{
				required:function(){
					if($('#q4:checked').length>0) {
						return true;
					} else {
						return false;
					}
				}
			},
			'regdata[stateprov]':{
				required:function(){
					if($('#q4:checked').length>0) {
						return true;
					} else {
						return false;
					}
				}
			},
			'regdata[zippostal]':{
				required:function(){
					if($('#q4:checked').length>0) {
						return true;
					} else {
						return false;
					}
				}
			}
		},
		errorElement: 'span',
		submitHandler: function(form){
			if ($('#page1').is(':visible')) {
				regOneHandler();
			} else {
				regTwoHandler(form);
			}
		}
	},
	wishemailval = {
		rules: {
			emailto: {
				required: true,
				email:true
			}
		},
		errorElement: 'span',
		submitHandler:function(form){wishlist_email_send(form);}
	};
	


var facebook = {
	
	xdreceiver: 'http://shopvogue.com/xd_receiver.htm',
	
	api: '7ac3e55cb8495f2dc79dc7a541f258d5',
	
	streamAttachment: {
	},
	
	stream: function(attachment, action, user_message_prompt,callback) {
		FB.init(facebook.api, facebook.xdreceiver);
		FB.Facebook.apiClient.users_hasAppPermission('publish_stream',
			function(results){
				if (results) {
					FB.Connect.streamPublish('', attachment, action,  null, user_message_prompt, callback, true);
				} else {
					FB.Connect.streamPublish('', attachment, action,  null, user_message_prompt, callback, false);
				}
			}
		);
	},
	
	getId: function () {
		fbid = $.cookie(facebook.api+'_user');
		//console.log('facebook.getId(), return '+fbid);
		return fbid;
	},
	
	setName: function() {
		//console.log('facebook.setname');
		var uid = facebook.getId();
		
		FB_RequireFeatures(["Api"], function(){
			var api = FB.Facebook.apiClient,
				uids = [uid],
				fields = ['first_name','last_name','pic_square'];
					
			FB.init(facebook.api, facebook.xdreceiver);
			
			api.users_getInfo(uids,fields,function(result){
				$.cookie('pic', result[0].pic_square, { path: '/'});
				$.cookie('fname', result[0].first_name, { path: '/'});
				$.cookie('lname', result[0].last_name, { path: '/'});
				
				name = result[0].first_name+' '+result[0].last_name;
			});
		});
	},//getName
	
	logout: function(){
		//console.log('facebook.logout()');
		FB_RequireFeatures(["Api"], function(){
		//	var api = FB.Facebook.apiClient;
			FB.init(facebook.api, facebook.xdreceiver);
			FB.Connect.logout(function(){window.location.reload();});
		});
	}
};


var user = {
	getName: function(){
		//console.log('user.getName()');
		if ($.cookie('fname') !== null) {
			name = $.cookie('fname')+' '+$.cookie('lname');
		} else {
			name = $.cookie('email');
		}
		return name;
	}
};


var login = {
	
	checkUserExists: function(context) {
		//console.log('login.checkUserExists('+context+')');
		var field = (context == 'fb') ? 'fb_id' : 'email',
			value = (context == 'fb') ? facebook.getId : $('#email_lf1').val(),
			data = {
				method:'userExists',
				field:field,
				value:value
			};
			
			if (context == 'fb') {//FB Branch
				$.cookie('isfb', 'yes', { path: '/'});
				facebook.setName();
				
				$.get(login.loginHandler,data,function(data){
					if (data) {
						login.goToFblogin();
					} else {
						login.goToLoginReg(null);
					}
				});//get
				
			} else {//Standard Branch
				uid = '';
				$.cookie('isfb', 'no', { path: '/'});
				$.cookie('pic', 'images/login_profilepic_standard.jpg', { path: '/'});
				data.password = $('#password').val();
				
				$.get(login.loginHandler,data,function(data){
					if (data) {
						login.goToLoginPw();
					} else {
						var email = $('#email_lf1').val();
						login.goToLoginReg(email);
					}
				});//get
				
			}//end standard branch
			
	},//checkUserExists
	
	goToLoginPw: function() {
		//console.log('login.goToLoginPw()');
		var email = $('#email_lf1').val();
		$('#page1').slideUp('fast',function(){
			
			
			$('#page2').slideDown('fast');
			$('#hiddenemail').val(email);
			$('#form_login').ajaxForm(function(data) { 
											   
				if (data == '1') {
					login.success(null); 
				} else {
					alert('Your password did not match');
				}
				return false;
			});
		});
	},//goToLoginPw

	goToFblogin: function () {
		//console.info('login.goToFblogin()');
		var fbid = facebook.getId();
		$.get(
			login.loginHandler,
			{
				method:'login',
				fbid:fbid
			},
			function(data){
				if (data == 1) {
					login.success(null);
				} else {
					alert('error:'+data);
				}
			}
		);
	},

	goToLoginReg: function(email) {
		//console.log('login.goToLoginReg('+email+')');
		$('#ajaxcontent').fadeOut('fast',function(){
			$('#smfcontent').load('login/login_2 #ajaxcontent',null,function(){
			
			if (uid != '') {$('#fb_id').val(uid);}
			
			$('#ajaxcontent').fadeIn('fast');
				$('#email_l2').val(email);
				$('#registration').validate(regform1);
			});
		});

	},//goToLoginReg

	goToLoginRegPg2: function() {
		//console.log('login.goToLoginRegPg2()');
		$('#page1').slideUp('fast',function(){
			$('#page2').slideDown('fast');
		});
	},//goToLoginRegPg2

	loginHandler: 'assets/snippets/loginhandlers.php',
	
	logOut: function() {
		//console.log('login.logOut()');
		
		$.cookie(facebook.api+'_user',null);
		$.cookie('uid', null, { path: '/'});
		$.cookie('pic', null, { path: '/'});
		$.cookie('fname', null, { path: '/'});
		$.cookie('lname', null, { path: '/'});
		$.cookie('email', null, { path: '/'});
		
		$('body').removeClass('logged_in');
		wishControl();
		
		if ($.cookie('isfb') != 'no') {
			$.cookie('isfb', 'no', { path: '/'});
			facebook.logout();
		} else {
			window.location.reload();
		}
		
	},
	
	postRegToFb: function() {
		//console.log('login.postRegToFb');
		var name = user.getName();
		var attachment = {
				'name':name+' just registered with the Vogue Pop Up Shop',
				'caption':"Visit the Vogue Pop Up Shop for the best holiday picks from Vogue advertisers.",
				'media':[{
					'caption':'Vogue',
					'type':'image',
					'href':'http://shopvogue.com/',
					'src':'http://shopvogue.com/images/login_profilepic_standard.jpg'
				 }]
			},
			action = [
			  { "text": "Visit Vogue's Pop Up Shop", "href": "http://shopvogue.com/"}			  
			 ],
			msg = 'I just registered for the Vogue Pop Up Shop 2009!';
			callback = function(){if(data) {window.location.reload();}};
		
		facebook.stream(attachment,action,msg,callback);
	},//postRegToFb
	
	success: function(fbprompt) {
		
		if ($.cookie('isfb')==='yes') {
			facebook.setName();
		}
		
		$('#ajaxcontent').fadeOut('fast',function(){
			$('#smfcontent').load('login/login_3 #ajaxcontent',null,function(){
				$('#ajaxcontent').fadeIn('fast',function(){
					
					if(fbprompt == 'yes') {
						login.postRegToFb();
					} else {
						$('body').addClass('logged_in').fadeTo(2000,1,function(){window.location.reload();});
					}
				});//ajaxcontent fadein
			});
		});
	}//success
	
};




function logOut(){
	login.logOut();
	return false;
}




  //Handlers - Login and Registration//
	
	
		function regTwoHandler(form){
			//alert(form);
			$(form).ajaxSubmit({
				success: function(data){
					if (data == 1) {
						var fbprompt = (uid != '') ? 'yes' : 'no';
						//console.info('fbprompt: '+fbprompt);
						login.success(fbprompt); 
					} else if (data == 'Error: 1062') {
						alert('Ooops, this email has already been registered.');
					} else if (data == '-1') {
						alert('Please provide your first name');
					} else if (data == '-2') {
						alert('Please provide your last name');
					} else if (data == '-3') {
						alert('Please make sure you provided a valide email');
					} else if (data == '-4') {
						alert('Please provide your address');
					} else if (data == '-5') {
						alert('Please provide your city');
					} else if (data == '-6') {
						alert('Please provide your state');
					} else if (data == '-7') {
						alert('The city, state, and zip combo you provided is not valid');
					} else if (data == '-8') {
						alert('Please provide your zip code');
					} else if (data == '-10') {
						alert('Ooops, this email has already been registered.');
					} else {
						alert('Oops, there was a problem accepting your submission. Please double check your info');
					}
				}//ajaxSubmit success
			});
		}//regTwoHandler
		
		function regOneHandler(){
			if ($.cookie('isfb') == 'yes') {
				//console.info('running #link_register live click, isfb');
				$.get(
					login.loginHandler,
					{
						method:'userExists',
						field:'email',
						value:$('#email_l2').val()
					},
					function(data){
						if (data) {
							var answer = confirm('You already have an account with this email. Connect your Facebook profile to this account?');
							if (answer) {
								var fbid = facebook.getId();
								$.get(
									login.loginHandler,
									{
										method:'addFb',
										fbid:fbid,
										email:$('#email_l2').val(),
										pw:$('#pw').val()
									},
									function(data){
										if (data == 1) {
											var fbprompt = (uid != '') ? 'yes' : 'no';
											//console.info('fbprompt: '+fbprompt);
											login.success(fbprompt);
										} else if (data == 2) {
											alert('Password did not match');
										}else {
											//console.warn('error: '+data);
										}
									}
								);
							} else {
								return false;
							}
						} else {
							//console.info('No email match; proceeding to registration.');
							login.goToLoginRegPg2();
						}
					}
				);
			//if fb
			} else {
				login.goToLoginRegPg2();
			}
		}//regOneHandler()
		
		
		function profilehandler() {
			$('#smfbox.profile a#submit').click(function(){
							
				if ($('#fbauth:checked').length>0) {
						$.get(
							login.loginHandler,
							{
								method:'fbremove',
								email:$.cookie('email')
							},
							function(){
								alert('Your Facebook account has been disassociated from the Vogue Pop Up Shop.');
								FB_RequireFeatures(["Api"], function(){FB.Facebook.apiClient.revokeAuthorization(null,function(){});});
								$('#smfclose').click();
								logOut();
								
							}
						);
					
				} else {
					if ($('#streamauth:checked').length===0) {
						FB_RequireFeatures(["Api"], function(){FB.Facebook.apiClient.revokeAuthorization(null,function(){});});
						alert('Comments and wish list additions will NOT automatically publish to your Facebook Stream.');
						$('#smfclose').click().fadeTo(1000,1,function(){window.location.reload();});
					} else {
						FB.Connect.showPermissionDialog('publish_stream',function(perms){
							$('#smfclose').click().fadeTo(1000,1,function(){window.location.reload();});
						});
					}
				}
				return false;
				
			});
		}
		
  //Handlers - Wishlist//
	
		function wishBlinkOut(){
			$('#wish_notification').fadeOut(100).fadeIn(75).fadeOut(50);
		}//wishBlinkOut()
		

		function wishlistAfterAdd(thisthing) {
			$('#wish_notification').fadeIn('slow');
			thisthing.removeClass('showajaxloader');
			$('body').fadeTo(5000,1,function(){
				wishBlinkOut();
			});
		}
	

		function wishlistRemove(clicked) {
			$(this).addClass('showajaxloader');
			var uid = $.cookie('uid'),
				iid = clicked.attr('rel'),
				grandpa = clicked.parent().parent();
			
			if(uid !== null){
				$.get(
					login.loginHandler,
					{
						method:'wishlist_remove',
						item_id:iid,
						uid:uid
					},
					function(data) {
						if (data == 1) {
							//inform them it was removed successfully
							$('#wish_notification').html('Item was successfully removed from your wish list.');
							grandpa.fadeOut(500);
						} else {
							//inform them there was a problem
							$('#wish_notification').html('There was a problem removing the item from your wish list.');
						}
					}
				);
			} else {
				$(this).removeClass('showajaxloader');
				$('#wish_notification').html('You have been logged out. Please log back in to delete an item from your wish list.');
				$('#wish_notification').fadeIn('slow');
				$('body').fadeTo(5000,1,function(){
					wishBlinkOut();
				});
			}			
		}//wishlistRemove

		
		function wishControl(){//display wishlist
			$('.lnk_wishlist').unbind();
			if($.cookie('uid') !== null){
				$('.lnk_wishlist').smfbox({
					content: 'wishlist?uid='+$.cookie('uid')+' #ajaxcontent',
					boxClass: 'wishlist',
					afterRender: function(){$('.wishlist-scroll').jScrollPane({scrollbarWidth:10});}
				});
			} else {
				$('.lnk_wishlist').click(function(){
					$('#wish_notification').html('Please log in to view your wish list.');
					$('#wish_notification').fadeIn('slow');
					$('body').fadeTo(5000,1,function(){
						wishBlinkOut();
					});
					return false;
				});
			}
		}
    
		function wishlist_email() {
			$('#w_email').fadeIn().validate(wishemailval);
		}
		
		function wishlist_email_send(form) {
			$(form).ajaxSubmit(function(){
				alert('Your wishlist has been sent');
				$('body').fadeTo(2000,1,function(){
					$('#w_email').fadeOut();
				});
			});
		}


		function wishlistAdd(id){
			$(this).addClass('showajaxloader');
			var uid = $.cookie('uid'),
			thisthing = $(this);
			
			if (uid === null || uid == '') {
				$('#wish_notification').html('There was a problem adding the item to your wish list.');
				//wishlistAfterAdd(thisthing);
			} else {
				$.get(login.loginHandler,
					{
						uid:uid,
						item_id:id,
						method:'wishlist_add'
					},
					function(data) {
						var notice = (data == 1) ? 'Item was successfully added to your wish list.' : 'You attempted to add an item already in your wish list.';
						$('#wish_notification').html(notice);

						if (data == 1 && $.cookie('isfb') == 'yes') {

						var prodimg = $('#featured_brand').attr('src'),
							name = $('#login_name').text(),
							attachment = {
								'name':name+' just added an item to a wishlist at the Vogue Pop Up Shop',
								'caption':$.cookie('fname')+' added '+$('h4').text()+' to their wish list',
								'media':[{
									'caption':'Vogue',
									'type':'image',
									'href':'http://shopvogue.com/',
									'src':'http://shopvogue.com/'+prodimg
								 }]
							},
							action = [
							  { "text": "Visit Vogue's Pop Up Shop", "href": window.location.toString()}			  
							 ],
							msg = 'I just added an item to a wishlist at the Vogue Pop Up Shop';
							
						var callback = ($.cookie('expasked') != 'yes') ? 
								function () {
									$.cookie('expasked', 'yes', { path: '/'});
									FB.Connect.showPermissionDialog('publish_stream',function(perms){
											wishlistAfterAdd(thisthing);
									});
								} :
								function(data) {
									wishlistAfterAdd(thisthing);
								};
						
						facebook.stream(attachment,action,msg,callback);

						} else {
							wishlistAfterAdd(thisthing);
						}
					}//get callback
				);//get
			}
		}//wishlistAdd()
			
  //Handlers - Comments//	
  
  
	function showCommentForm(){
		if($.cookie('uid') !== null){
			$('#comment_form').fadeIn('fast');
			$('#comform').ajaxForm(function(data){
				if (data == 1) {
					alert('Thank you - your comment has been submitted');
					if ($.cookie('isfb') === 'yes' && document.getElementById('comtofb').checked === true) {
						
						var prodimg = $('#featured_brand').attr('src'),
							name = $('#login_name').text(),
							attachment = {
								'name':name+' made a comment on '+$('h4').text()+' at the Vogue Pop Up shop',
								'caption':$('#comment_input').val(),
								'media':[{
									'caption':'Vogue',
									'type':'image',
									'href':'http://shopvogue.com/',
									'src':'http://shopvogue.com/'+prodimg//'http://shopvogue.com/images/login_profilepic_standard.jpg'
								 }]
							},
							action = [
							  { "text": "Visit Vogue's Pop Up Shop", "href": window.location.toString()}			  
							 ],
							msg = 'I just made a comment on the Vogue Pop Up Shop';
							
						if ($.cookie('expasked') != 'yes') {
							//console.log('1');
							callback = function(data) {
									FB.Connect.showPermissionDialog(
										'publish_stream',
										function(){
											window.location.reload();
										}//function()
									);//fb.showPermissionDialog
							};//callback
							
							$.cookie('expasked', 'yes', { path: '/'});
						} else {
							//console.log('2');
							callback = function(data){
								window.location.reload();
							};
						}//if have not asked about permissions
						facebook.stream(attachment,action,msg,callback);
					} else {
						window.location.reload();
					}//if/else isfb
				} else {
					alert('there was an error submitting your comment');
				}//if/else data ==1
			});
        } else {
            $('#comment_error').html('You must be logged in to comment.<br/><br/><a class="lnk_login_comments" href="login/login_1"><img width="70" height="25" alt="Log in" src="images/lnk_login.png"/></a>');
            $('#comment_error').fadeIn('fast',function(){
				$('.lnk_login_comments').click(function(){$('.lnk_login').click();return false;});		   
			});
        }
    }//showCommentForm()
	
	function comment_flag(id) {
		//console.info(cflag);
		if (cflag != 1) {
			cflag = 1;
			//console.info('comment flag set: '+cflag);
			$.get(
				login.loginHandler,
				{
					method:'comment_flag',
					id:id
				},
				function(data) {
					if (data == 1) {
						//inform them it was removed successfully
						alert('This comment has been flagged');
					} else {
						//console.warn('error flagging comment');
					}
				}
			);
		}
	}//comment_flag()

  //Handlers - Special Offers//
	function toggleSO(){
		if(soopen){
			$('#special_offer_box').fadeOut('fast');
			soopen = false;
		} else {
			$('#special_offer_box').fadeIn('fast');
            soopen = true;
			/*var loc = window.location.toString(),
				hash = window.location.hash;*/
			pageTracker._trackPageview(window.location.toString()+'/special_offer');
		}
	}//toggleSO


$(function(){//Document Ready
/*Document Ready Variables*/		   
	var brandlist = $('#bybrand_list'),
		brandimg = $('#bybrand_img'),
		brandnav = $('#nav_brand'),
		breadcrumb = $('#breadcrumb'),
		detailbox = {
			overlay:$('#detailoverlay'),
			box:$('#detailbox')
		},
		detail_holder = $('#detail_holder'),
		deptimg = $('#bydept_img'),
		deptlist = $('#bydept_list'),
		deptnav = $('#nav_dept'),
		detail_url = window.location.hash,
		featured_brand = $('#featured_brand'),
		homediv = false,
		thumbs = $('#thumbs'),
		idfromcookie = $.cookie('uid'),
		picfromcookie = $.cookie('pic');

/*Document Ready Initializations*/
	wishControl();
	$('.scroll-pane').jScrollPane({scrollbarWidth:7});
		
	//States of children of the scroll pane elements (must be initialized AFTER scrollpane)
	brandlist.hide().css('visibility','visible');
	deptlist.hide().css('visibility','visible');
  
	if ($('#home').length>0) {homediv = true;}
	
/*Document Ready Handlers*/	

  //Handlers - Detail Pages//
	function showDetail(target) {
		$('#jump_holder').fadeOut();
		
		detail_holder.load(target+' #detail_content',null,function(){
			$('#ajax1').hide();
			$('#ajax2').hide();
			var alias = $('#product_alias').text();
			window.location.hash = alias;
			
			var url = window.location.toString();
			var patt1=/stag/gi;
			
			detail_holder.fadeIn('fast',function(){
				$('.detail-scroll').jScrollPane({scrollbarWidth:7});												 
			});
			breadcrumb.fadeIn('fast');
			pageTracker._trackPageview(target);
		});
	}//showDetail()

	function setupShareLinkFromAjax() {
		var currentx= parseInt($('#cta_buy').offset().left,10)+136,
			currenty= parseInt($('#cta_buy').offset().top,10)-270;
		try {
			
			SHARETHIS.shareables[0].properties.url= window.location.toString();
			SHARETHIS.shareables[0].popup();
			$('#stwrapper').css({'top': '206px', 'left': currentx+'px'}).show();

		} catch (err) {
			//console.warn('share this error: '+err);
		}
	}//setupShareLinkFromAjax
	
	function brandnavhandler() {
		if (brandlist.is(':visible')) {
			brandlist.slideUp('fast',function(){
				if (homediv) {brandimg.show();}
			});
		} 
		else {
			if (homediv) {
				brandimg.hide('fast',function(){
					brandlist.slideDown('fast');
				});
			} else {
				if(deptlist.is(':visible')){
					deptlist.slideUp();
				}
				brandlist.slideDown('fast');
			}
		}		
	}//brandnavhandler
	
	function deptnavhandler() {
		if ($('#home').length>0) {homediv = true;}
		if (deptlist.is(':visible')) {
			deptlist.slideUp('fast',function(){
				if (homediv) {deptimg.show();}
			});
			return false;
		} 
		else {
			if (homediv) {
				deptimg.hide('fast',function(){
					deptlist.slideDown('fast');
				});
			} else {
				if(brandlist.is(':visible')){
					brandlist.slideUp();
				}
				deptlist.slideDown('fast');
			}
		}
	}//deptnavhandler
	
	$('#shop a').click(function(){
		if ($(this).attr('href')=='') {
			return false;
		}
	});

/*Events - Pretty much all in Document Ready*/
	
	//Toggle browse list visibility 
		brandnav.click(function(){
			brandnavhandler();
			return false;
		});

		deptnav.click(function(){
			deptnavhandler();
			return false;
		});
	
		$('a.close').click(function(){
			$(this).parent().slideUp('fast');
			return false;
		});

	//Jump page: Toggle Detail View
	
		$('.thumb').click(function(){
			var targeta = $(this).find('a'),
				target = targeta.attr('href');
			showDetail(target);
			return false;
		});		
		
		breadcrumb.click(function(){
			breadcrumb.fadeOut('fast');
			detail_holder.fadeOut('fast',function(){
				$('#jump_holder').fadeIn();
				$('#ajax1').show();
				$('#ajax2').show();
				detail_holder.html('');
				window.location.hash = '';
			});
			
			return false;
		});		

		if (detail_url) {
			var s = window.location.toString();
				if (s.indexOf("#banner") === -1) {
					var aUrl = s.split('#'),
						targetUrl = aUrl[aUrl.length-1];
						target = targetUrl.replace(/UU/g,'/');
						showDetail(target);
				}
			//console.log(targetUrl.replace(/UU/g,'/'));
		}
		
	//Detail Page: Share
	$('#cta_share').live('click',function(){ 
		setupShareLinkFromAjax();		
		return false;
	});
	
	$('#cta_buy').live('click',function(){ 
		pageTracker._trackPageview(window.location.toString()+'/buy_now');	
	});
	
	//Detail Page: Lightbox
		$('#featured_zoom').live('click',function(){
			detailbox.overlay.css('opacity','0.01').fadeIn('fast',function(){
				detailbox.box = $('#detailbox');
				$('#detailcontent img').attr({
					style: "width:790px;height:790px;left:0;top:0;border:0;"
				});
				detailbox.box.fadeIn();
			});
			return false;
		});
		
	
		$('#detailoverlay').live('click',function(){
			detailbox.box.fadeOut('fast',function(){
				detailbox.overlay.fadeOut();										   
			});							
			return false;
		});
	
		$('#detailclose').live('click',function(){
			detailbox.box.fadeOut('fast',function(){
				detailbox.overlay.fadeOut();										   
			});							
			return false;
		});
	
	//Comments
		//Controls comment visibility.
		$('.show_comments').live('click',function(){
			$('#comments-scroll').jScrollPane({scrollbarWidth:7});
			$('#comments-scroll').fadeIn();
		});
		$('.hide_comments').live('click',function(){
			$('#comments-scroll').fadeOut(500);
			$('body').fadeTo(5000,1,function(){
				$('#comments-scroll').jScrollPaneRemove();
			});
		});
		$('.add_comment_p').live('click',function(){
			$('#comments-scroll').jScrollPane({scrollbarWidth:7});
			showCommentForm();
			$('#comments-scroll').fadeIn();
		});
		$('.add_comment').live('click',function(){
			showCommentForm();
		});
		
		$('#com_logout').live('click',function(){logOut();});
		
		$('a.flag').live('click',function(){
			var id = $(this).attr('rel');
			comment_flag(id);
			return false;
		});

	//Log in pages
			
		//Attach lightbox launch to log in button
		$('.lnk_login').smfbox({
			boxClass: 'login',
			content: 'login/login_1 #ajaxcontent',
			beforeRender: function(){
				FB.init(facebook.api, facebook.xdreceiver);
				try {
				$("#lf1").validate(login1val);
				} catch(err) {
					alert(err);
				}
			},
			afterRender:function(){
				if (!$.support.scriptEval) {//For IE only
					$("#email_lf1").val('your email').focus();
					$('#sbm_login1').click(function(){
						$('#email_lf1').submit();
					});
				}
			}
		});

		//Provide back button functionality from Login 2 to Login 1
			$('#smfcontent a.back').live('click',function(){
				var target = $(this).attr('href');
				$('#ajaxcontent').fadeOut('fast',function(){
					$('#smfcontent').load(target +'#ajaxcontent',null,function(){FB.init(facebook.api, facebook.xdreceiver);});
				});
				return false;
			});
			
		//Login In View 2, transition to page 2
		$('#lnk_register').live('click',function(){
			$('#registration').submit();
			return false;
		 });
	
	
		$('#lnk_profile').smfbox({
			boxClass: 'profile',
			content: 'login/user-profile #ajaxcontent',
			beforeLoad: FB.init(facebook.api, facebook.xdreceiver),
			beforeRender: function(){
				var permission = 'publish_stream'
				FB.Facebook.apiClient.users_hasAppPermission(permission,
					function(results){
						if (results) {
							$('#streamauth').attr('checked','checked');
						} else {
							$('#streamunauth').attr('checked','checked');
						}
					}
				);
				/*if (auto === true) {
					$('#streamauth').attr('checked','checked');
				} else {
					$('#streamunauth').attr('checked','checked');
				}*/
				
				
				if ($('body.fb').length===0) {
					FB.init(facebook.api, facebook.xdreceiver);
				}
				
			},
			afterRender: function() {
				profilehandler();
				return false;
			}
		});
		
		
		$('#lnk_logout').live('click',function(){logOut();return false;});

	//Wishlist 
	
		//add to wishlist
		$('#cta_wishlist').live('click',function(){
			var id = $(this).attr('rel');
			wishlistAdd(id);
			pageTracker._trackPageview(window.location.toString()+'/wishlist_add');			
			return false;
		});
		
		//remove from wishlist
		$('.wishlist_remove').live('click',function(){
			var clicked = $(this);
			wishlistRemove(clicked);
			return false;
		});
		
		$('#wish_notification').click(function(){
			$('#wish_notification').fadeOut('fast');
		});
		
		$('.wishlist_email').live('click',function(){wishlist_email();return false;});
	
// Special Offer notification toggle
    $('#cta_offer').live('click',function(){
        toggleSO();
    });
	
	$('#featured_home_container').cycle({timeout:4000}).css('visibility','visible');
	
	
});//end document ready wrapper and end event listeners
