
$(document).ready(function() {
	
	$("#divProductListing input[type='text'],").change(function(e) {
		id = $(this).attr('id');
		quantity = $("#" + id).val();
		notes = $("#notes").val();
		couponCode = $("#couponCode").val();
		
		arr = id.split('__');
			
		if (arr[0] == 'quantity') {
			$.post("/shoppingcart/updateQuantity", {quantity:quantity, productId:arr[1], notes:notes },
			function(data){
				var $alert = $("#message__" + arr[1]);
				if (data == 'yes') {
					document.location = uri;
					/*
					toggleMessage($alert, "Product successfully added in cart", "", "");
					var imageId = "#image_addToCart__" + arr[1];
					$(imageId).attr("src", "/images/added_to_cart.PNG");
					
					$.post("/shoppingcart/getProductCountInCart", { },
					function(data){
						$("#cartCount").html(data + ((data > 1) ? ' items' : ' item') + ' in your cart');
					});
					*/
				} else {
					//toggleMessage($alert, "Product could not be added in cart", "", "");
				}
			});
		}
		
	});
	
	$("#divProductListing a").click(function(e) {
		
		id = $(this).attr('id');
		notes = $("#notes").val();
		
		if ( id == "" ) {
			// Follow href
			
		} else {
			e.preventDefault();
			id = $(this).attr('id');
			
			arr = id.split('__');
			
			if (arr[0] == 'addToCart') {
				
				$.post("/shoppingcart/addToCart", {q:arr[1] },
				function(data){
					var $alert = $("#message__" + arr[1]);
					
					if (data == 'yes') {
						toggleMessage($alert, "Product successfully added in cart", "", "");
						var imageId = "#image_addToCart__" + arr[1];
						$(imageId).attr("src", "/images/added_to_cart.PNG");
						
						$.post("/shoppingcart/getProductCountInCart", { },
						function(data){
							$("#cartCount").html(data + ((data > 1) ? ' items' : ' item') + ' in your cart');
						});
					} else if (data == 'duplicate') {
						toggleMessage($alert, "Product already added in cart", "", "");
					} else {
						toggleMessage($alert, "Product could not be added in cart", "", "");
					}
				});
			} else if (arr[0] == 'addToFavorites') {
				
				var $alert = $("#message__" + arr[1]);
				if(userId != '') {
					$.post("/favorite/addToFavorites", {q:arr[1] },
					function(data){
						
						if (data == 'yes') {
							toggleMessage($alert, "Product successfully added in Favorite List", "", "");
							var imageId = "#image_addToFavorites__" + arr[1];
							$(imageId).attr("src", "/images/added_to_favorite.PNG");
							
						} else if (data == 'duplicate') {
							toggleMessage($alert, "Product already added in Favorite List", "", "");
						} else {
							toggleMessage($alert, "Product could not be added in Favorite List", "", "");
						}
					});
				} else {
					openLoginPoup('addToFavorites(' + arr[1] + ')', uri);
				}
			
			} else if (arr[0] == 'deleteFromFavorite') {
				
				var $alert = $("#message__" + arr[1]);
				if(userId != '') {
					$.post("/favorite/deleteFavorite", {q:arr[1] },
					function(data){
						if (data == 'yes') {
							toggleMessage($alert, "Product deleted from Favorite List", uri, "");
						} else {
							toggleMessage($alert, "Product cound not be deleted from Favorite List", "", "");
						}
					});
				}
			} else if (arr[0] == 'deleteFromCart') {
				
				var $alert = $("#message__" + arr[1]);
				$.post("/shoppingcart/deleteFromCart", {q:arr[1], notes:notes },
				function(data){
					
					if (data == 'yes') {
						toggleMessage($alert, "Product deleted from Shopping Cart", uri, "");
					} else {
						toggleMessage($alert, "Product cound not be deleted from Shopping Cart", "", "");
					}
				});
				
			} else if (arr[0] == 'askUs') {
				
				if(userId != '') {
					askUs(arr[1]);
					
				} else {
					openLoginPoup('askUs(' + arr[1] + ')');
				}
				
			} else if (arr[0] == 'quickBuy') {
				
				alert("Quick Buy clicked");
				
			}
		}
	});
	
	$("#divFavoriteListing a").click(function(e) {
		id = $(this).attr('id');
		if ( id == "" ) {
			// Follow href
		} else {
			e.preventDefault();
			id = $(this).attr('id');
			
			arr = id.split('__');
			
			if (arr[0] == 'addToCart') {
				
				$.post("/shoppingcart/addToCart", {q:arr[1] },
				function(data){
					var $alert = $("#message__" + arr[1]);
					if (data == 'yes') {
						//toggleMessage($alert, "Product successfully added in cart", "", "");
						var imageId = "#image_addToCart__" + arr[1];
						$(imageId).attr("src", "/images/added_to_cart.PNG");
						
						$.post("/shoppingcart/getProductCountInCart", { },
						function(data){
							$("#cartCount").html(data + ((data > 1) ? ' items' : ' item') + ' in your cart');
						});
						
					} else if (data == 'duplicate') {
						toggleMessage($alert, "Product already added in cart", "", "");
					} else {
						toggleMessage($alert, "Product could not be added in cart", "", "");
					}
				});
				
			} 
		}
	});
	
	
	$("#divProductListing").children('div').each(function(index) {
		levelOneDiv = $(this);
		id = $(levelOneDiv).attr('id');
		
		if (id != "") {
			$(levelOneDiv).children('div').each(function(index1) {
				levelTwoDiv = $(this);
				id = $(levelTwoDiv).attr('id');
				
				if (id != "") {
					$(levelTwoDiv).children('a').fancybox({
						'titlePosition'	: 'inside'
					});
				}
			});
		}
	});
	
	
});

function addToFavorites(productId) {
	var $alert = $("#message__" + productId);
	$.post("/favorite/addToFavorites", {q:productId },
	function(data){
		
		if (data == 'yes') {
			toggleMessage($alert, "Product  successfully added in Favorite List", uri, "");
		} else if (data == 'duplicate') {
			toggleMessage($alert, "Product already added in Favorite List", uri, "");
		}
	});
}


function askUs(productId) {
	var $alert = $("#message__" + productId);
				
	$.post("/product/getProductFromIdJson", {q:productId },
	function(data){
	
		var html  = 
				'<form name = "askUsForm" id = "askUsForm" action = "" method = "post">'+
				'	<div>'+
				
				'		<div class="padtop10">'+
				'			<div class="label flt"><h3>Ask Us </h3></div>'+
				'			<div class="clear"></div>'+
				'		</div>'+
				'		<div class="clear"></div>'+
				
				'		<div id = "askUsDiv">'+
				'		<div id = "askUsMessage" class="validation_message" style = "display:none;" align="center"></div>'+
				
				'		<div class="padtop10">'+
				'			<div class="label flt">To </div>'+
				'			<div class="flt wid3" style="width: 346px;"><input name="toEmail" id = "toEmail" type="text"  value = "Vendor" class="txtinput2" readonly/><br/></div>'+
				'			<div class="clear"></div>'+
				'		</div>'+
				'		<div class="clear"></div>'+
				
				'		<div class="padtop10">'+
				'			<div class="label flt">Subject<span>*</span></div>'+
				'			<div class="flt wid3" style="width: 346px;"><input name="subject" id = "subject" type="text"  value = "[#'+data.productId+'] '+data.productName + (data.brand != "" ? " - " + data.brand : "" ) + (data.weight != "" ? " - " + data.weight : "" ) +'" class="validate[required] txtinput2"/><br/></div>'+
				'			<div class="clear"></div>'+
				'		</div>'+
				'		<div class="clear"></div>'+
				
				'		<div class="padtop10">'+
				'			<div class="label flt">Body<span>*</span></div>'+
				'			<div><textarea  rows="5" cols="30" name="message" id="message" class="validate[required]"></textarea><br/></div>'+
				'			<div class="clear"></div>'+
				'		</div>'+
				'		<div class="clear"></div>'+
				
				'		<div class="padtop10">'+
				'			<div class="flt wid3 terms_conditions">'+
				'				<div class="padtop10"><span class="button"><a href="" id = "submitAskUsButton">Send</a></span></div>'+
				'			</div>'+
				'			<div class="clear"></div>'+
				'		</div>'+
				'		<input type="hidden" id="productId" value="'+data.productId+'" >'+
				'		<input type="hidden" id="toUserId" value="'+data.vendorId+'" >'+
				'		<div class="clear"></div>'+
				'		</div>'+
				'	</div>'+
				'</form>';
		
		$.fancybox(
			html,
			{
	        	'hideOnOverlayClick': false,	
	        	'modal'				: false,
	        	'enableEscapeButton' : false,
	        	'autoDimensions'	: false,
				'width'         	: 500,
				'height'        	: 300,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				onComplete	:	function() {
            		reinitializeAskUsFormEvent();
				},
				onClosed	:	function() {
            		if (userId == '') {
            			document.location = uri;
            		}
				}
			}
		);
	},
	"json");
}

function reinitializeAskUsFormEvent() {
	
	$("#submitAskUsButton").click(function(e) {
		e.preventDefault();
		$("#askUsForm").submit();
	});
	
	$("#askUsForm").submit(function(e) {
		e.preventDefault();
		
		if ($("#askUsForm").validationEngine('validate', {scroll: false}) ) {
		
				$.post("/email/saveMessage", { 
					subject: $('#subject').val(),
					message: $('#message').val(),
					productId: $('#productId').val(),
					toUserId: $('#toUserId').val()
				},
				function(data){
					if (data == 'yes') {
						$("#askUsDiv").html(
						'<div class="clear"></div><br />'+
						'<div class="validation_message" align="center">Thanks for the enquiry. Vendor shall get back to you asap.<br />Please check your Inbox for replies later.</div>'+
						'<div class="padtop10" align="center"><span class="button"><a href="" id = "fancy_close" onClick="parent.jQuery.fancybox.close();">Close</a></span></div>'
						);
					} else {
						var $alert = $("#askUsMessage");
						toggleMessage($alert, "Email not sent", "", "");
					}
				});
					
		} else {
				
			return false;
		}
		
	});
}


	
