/**
 * Global Giggle Javascript file
 */

/**
 * Registry link rewrite to JSON and Dialog usage
 */
var current_url = window.location.href;
jQuery(document).ready(function(){
	var topsitenav = jQuery("#top-site-nav");
	/*
	 * Adding alertContaner div for alerts with app.dialog
	 */
	jQuery('body').append(jQuery('<div/>').attr('id','alertContainer').css('display','none').css('text-align','center'));
	
	/* 
	 * Add own click behavior to "Add To Registry" button
	 */ 
	jQuery('.addtoregistry').live('click', function(e){
		var _this = jQuery(this);
		e.preventDefault();
		if (jQuery(this).hasClass("cartbuttondisable")){
			return;
		}
		if (jQuery(this).attr("subproduct") != undefined) {
			var AttrSubProduct = jQuery(this).attr("subproduct");	
		} else {
			var AttrSubProduct = "";
		}
		//check for personalize option
		 
		var personalize = jQuery("#personalize");
		if (personalize.val() != null){
			if (personalize.val().length == 0){
				
				jQuery('.personalize-dialog').dialog({
			   		bgiframe: true,
					autoOpen: false,
					width: 500,
			    	resizable: false
				});
				jQuery('.personalize-dialog').dialog('open');
				return;
			}	
		}
		//close dialog window
		jQuery("#QuickViewDialog").dialog("close");
		
		app.ajax.getJson({
			url: app.URLs.regActive,
			callback: function(data) {
				if (!data || data.status == 'error') {
					if (!data.authenticated) {
						// post ProductID to put it to Registry
						if (app.ProductCache.selectedVar == null || app.ProductCache.selectedVar.id == null){
							var pid = app.ProductCache.pid;
						} else {
							var pid = app.ProductCache.selectedVar.id;
						}
						//set option for Special Product Set
						params = "";											
						if (app.ProductCache.specialProductSet == true){
							var spsID = "";
							for (var i = 0; i<app.ProductCache.subProducts.length; i++){
								spsID += (spsID == "" ? "" : ",") + app.ProductCache.subProducts[i].selectedVar.id;
							}
							params += "?childPids=" + spsID;
							params += "&specialProductSet=true";
							params += "&Quantity=" + jQuery(".quantitySet").val();
							var productImg = jQuery(".productdetailcolumn div.productimage img").attr("src");
							productImg = productImg.split("?");
							params += "&specialProductSetImage=" + jQuery("#imagepath").val;
							params += "&specialProductId=" + pid +"-"+ (new Date()).getTime();
							params += "&ProductID=" + pid;
						}else{
							params += "?ProductID=" + pid + "&Quantity=" + jQuery(".quantityinput").val();
						}
						window.location = app.URLs.loginAdd + params;

						/*jQuery('#alertContainer').text('You are not authenticated').append(jQuery('<br/>')).append(jQuery('<br/>')).append(jQuery('<a/>').attr('id','alertOkButton')).dialog({dialogClass:'alertdialog',width:300,resizable:false,modal:true}).dialog('open');
						if (typeof(data.redirect) != 'undefined') {
							jQuery('#alertOkButton').text('Continue').attr('href', data.redirect).attr('class', 'btn-continue img-button');
						} else {
							jQuery('#alertOkButton').text('Continue').click(function(e){
								e.preventDefault();
								jQuery('#alertContainer').dialog('close');
							});
						}*/
						
					}
				} else {
					if (data && data.registry && data.registry.id != undefined && data.registry.id !== null) {
						// we have active registry
						// post ProductID to put it to Registry
						if (app.ProductCache.selectedVar == null || app.ProductCache.selectedVar.id == null){
							var pid = app.ProductCache.pid;
						} else {
							var pid = app.ProductCache.selectedVar.id;
						}
						if(app.ProductCache.subProducts.length > 0 && AttrSubProduct != ""){
							pid = app.ProductCache.subProducts[AttrSubProduct].selectedVar.id;
						}

						var postData = { ProductID: pid, ProductListID: data.registry.id, Quantity: jQuery(".quantityinput").val() };
						//set option for Special Product Set
						if (app.ProductCache.specialProductSet == true){
							var spsID = "";
							for (var i = 0; i<app.ProductCache.subProducts.length; i++){
								spsID += (spsID == "" ? "" : ",") + app.ProductCache.subProducts[i].selectedVar.id;
							}
							postData.childPids = spsID;
							postData.Quantity = jQuery(".quantitySet").val();
							postData.specialProductSet = true;
							var allVar = app.ProductCache.pid;
							jQuery(".swatchesdisplay").each(function(){
								if (jQuery(this).find("li.selected a").length > 0){
									allVar += "-"+jQuery(this).find("li.selected a").attr("href");
								}
							});
							var productImg = allVar;
							productImg = productImg.split("?");
							postData.specialProductSetImage = jQuery("#imagepath").val();
							postData.specialProductId = pid +"-"+ (new Date()).getTime();
						}
						//set all products id from product set
						if (app.ProductCache.subProducts.length > 0 && app.ProductCache.specialProductSet != true && _this.hasClass("allproducttoregistry")){
							var productsID = "";
							var Quantity = "";
							for (var i = 0; i<app.ProductCache.subProducts.length; i++){
								productsID += (productsID == "" ? "" : ",") + app.ProductCache.subProducts[i].selectedVar.id;
								Quantity += (Quantity == "" ? "" : ",") + app.ProductCache.subProducts[i].selectedOptions.Quantity;
							}
							postData.childPids = productsID;
							postData.Quantity = Quantity;

						}
						
						if (personalize.val() != null){
							postData.personalized = personalize.val();
						}
						jQuery.ajax({
							type: 'post',
							url: app.URLs.regAdd,
							data: postData,
							dataType: 'json',
							success: function(data) {
								if(!data || typeof(data.status) == 'undefined') {
									alert("Server error!");
									return false;
								}
	
								if (data.status == 'error') {
									alert("Couldn't save event information due to form encountered errors");
									return false;
								} else {
									// data is saved
									document.location.reload();
								}
								return true;
							},
							failure: function(){
								alert("Server connection failed!");
							},
							error : function(){
								alert("Server error!");
							}
						});
					} else {
						// we have no active registry. get registry list
						if(!jQuery('#registrylist').dialog('isOpen')) {
							app.ajax.getJson({
								url: app.URLs.regList,
								callback: function(data) {
									if (!data || data.status == 'error') {
										if (!data.authenticated) {
											jQuery('#alertContainer').text('You are not authenticated').append(jQuery('<br/>')).append(jQuery('<br/>')).append(jQuery('<a/>').attr('id','alertOkButton')).dialog({dialogClass:'alertdialog',width:300,resizable:false,modal:true}).dialog('open');
											if (typeof(data.redirect) != 'undefined') {
												jQuery('#alertOkButton').text('Continue').attr('href', data.redirect).attr('class', 'btn-continue img-button');
											} else {
												jQuery('#alertOkButton').text('Continue').click(function(e){
													e.preventDefault();
													jQuery('#alertContainer').dialog('close');
												});
											}
										}
										return false;
									} else {
										//if not registry redirect to the create registry 
										if (data.registry.length == 0){
											//set option for Special Product Set
											params = "";											
											if (app.ProductCache.specialProductSet == true){
												var spsID = "";
												for (var i = 0; i<app.ProductCache.subProducts.length; i++){
													spsID += (spsID == "" ? "" : ",") + app.ProductCache.subProducts[i].selectedVar.id;
												}
												params += "?childPids=" + spsID;
												params += "&specialProductSet=true";
												params += "&Quantity=" + jQuery(".quantitySet").val();
												var productImg = jQuery(".productdetailcolumn div.productimage img").attr("src");
												productImg = productImg.split("?");
												params += "&specialProductSetImage=" + jQuery("#imagepath").val();												
												params += "&specialProductId=" + app.ProductCache.selectedVar.id +"-"+ (new Date()).getTime();
												params += "&ProductID=" + app.ProductCache.selectedVar.id;
											}else{
												params += "?ProductID=" + app.ProductCache.selectedVar.id + "&Quantity=" + jQuery(".quantityinput").val();
											}
											window.location = app.URLs.loginAdd + params;
											return false;
										}
										// display registry list dialog
										var el = jQuery('#registrylist').get(0);
										jQuery('#registrylists').empty().append(jQuery('<ul/>').attr('id','reglists'));
										// add list of items to div
										jQuery.each(data.registry, function(key, val){
											if (val != null) { // this 'if' for IE 7
												jQuery('#reglists').append(
													jQuery('<li/>').append(
														jQuery('<label/>').text('Registry # '+val.customID+', '+val.name+', '+val.date).prepend(
															jQuery('<input/>').attr('name','selectedListID').attr('type','radio').attr('checked', (key==0 ? 'checked' : '')).val(val.id)
														)
													)
												);
											}
										});
										jQuery(el).show().dialog({width:600,resizable:false,modal:true}).dialog('open');
										return false;
									}
								},
								failure: function(){
									alert("Server connection failed!");
								},
								error : function(){
									alert("Server error!");
								}
							});
						}
					}
				}
			},
			failure: function(){
				alert("Server connection failed!");
			},
			error : function(){
				alert("Server error!");
			}
		});
	});
	
	/*
	 * Add click behavior to "Registry List" Modal window Submit button
	 */
	jQuery('#registrysubmit').live("click", function(){
		if (app.ProductCache.selectedVar == null || app.ProductCache.selectedVar.id == null){
			var pid = app.ProductCache.pid;
		} else {
			var pid = app.ProductCache.selectedVar.id;
		}
		var rid = jQuery('[name=selectedListID]:checked').val();
		
		if (!rid) {
			// registry ID is not selected
			alert('Please select one registry from registry list');
		} else {
			var postData = { ProductID: pid, ProductListID: rid.split("|")[0], Quantity: jQuery(".quantityinput").val(), personalized: jQuery("#personalize").val() };
			//set option for Special Product Set
			if (app.ProductCache.specialProductSet == true){
				var spsID = "";
				for (var i = 0; i<app.ProductCache.subProducts.length; i++){
					spsID += (spsID == "" ? "" : ",") + app.ProductCache.subProducts[i].selectedVar.id;
				}
				postData.childPids = spsID;
				postData.specialProductSet = true;
				postData.Quantity = jQuery(".quantitySet").val();
				var productImg = jQuery(".productdetailcolumn div.productimage img").attr("src");
				productImg = productImg.split("?");
				postData.specialProductSetImage = jQuery("#imagepath").val();
				postData.specialProductId = pid +"-"+ (new Date()).getTime();
			}
			jQuery.ajax({
				type: 'post',
				url: app.URLs.regAdd,
				data: postData,
				dataType: 'json',
				success: function(data) {
					if(!data || typeof(data.status) == 'undefined') {
						alert("Server error!");
						return false;
					}

					if (data.status == 'error') {
						alert("Couldn't save event information due to server errors");
						return false;
					} else {
						// data is saved - we need to reload page
						jQuery('.ui-dialog').slideUp();
						
						window.location.href=app.util.appendParamToURL(app.URLs.getProductUrl, "pid", pid);
					}
					return true;
				},
				failure: function(){
					alert("Server connection failed!");
				},
				error : function(){
					alert("Server error!");
				}
			});
		}
	});

	/* 
	 * Add own click behavior to "Exit from Registry Mode" button
	 */ 
	jQuery('.rtoolbar_exit a').click(function(e){
		e.preventDefault();
		app.ajax.getJson({
			url: app.URLs.registryExit,
			data: {},
			callback: function(data) {
				if (data.success) {
					jQuery('[id=registrytoolbar]').slideUp().remove();
				}
			}
		});
	});
	
	/*
	 * Cancel Button handler on Delete Registry
	 */
	jQuery('#cancelRegistry').click(function(){
		jQuery('#giftregistrydeletedialog').dialog('close');
	});

	/*
	 * Customer Care Link Popup
	 */
	jQuery('.customerservice').click(function(e){
		e.preventDefault();
		jQuery('#customerservice').dialog({
	   		bgiframe: true,
			autoOpen: false,
			modal: true,
			width: 500,
	    	resizable: false
		});
		jQuery('#customerservice').dialog('open');
	});

	/*
	 * Registry Toolbar: dropdown menu for get started button 
	 */
	jQuery('.registrytoolbar .btn-get-started').click(function() {
		jQuery(this).toggleClass('opened');
		jQuery(this).next().toggle();
		return false;
	});

	/*
	 * My Registry: dropdown menu for get started button 
	 */
	jQuery('.registry .btn-get-started').click(function() {
		jQuery(this).toggleClass('opened');
		jQuery(this).next().toggle();
		return false;
	});

	/*
	 * My Registry: dropdown menu for add gifts button 
	 */
	jQuery('.registry .registryactions .btn-add-gifts').click(function() {
		jQuery(this).toggleClass('opened');
		jQuery(this).next().toggle();
		return false;
	});

	/*
	 * Navigate to purchases tab in Agent Mode
	 */
	jQuery('.purchases a').click(function(e){
		e.preventDefault();
		jQuery('#navPurchases').submit();
	});

	/*
	 * Styled selectboxes handle
	 */
	jQuery('select').change(function(){
		jQuery(this).parent().parent().find('.styledselectbox:first').text(jQuery(this).find("option:selected").text());
	})
	// init styled selectboxes values
	var selects = jQuery('select');
	jQuery.each(selects,function(i,el){
		jQuery(el).parent().parent().find('.styledselectbox:first').text(jQuery(el).find("option:selected").text());
	});
	
	/*
	 * Handle closeout redio-buttons
	 */
	jQuery('.eventtopcsclosed input').click(function(){
		postData = { ProductListID : jQuery(this).attr('id'), status: jQuery(this).val(), csr: 'true' };
		jQuery.ajax({
			type: 'post',
			url: app.URLs.registryClose,
			data: postData,
			dataType: 'json',
			success: function(data) {
				if(!data || typeof(data.success) == 'undefined') {
					alert("Server error!");
					return false;
				}

				if (!data.success) {
					alert("Couldn't save information due to server errors");
					return false;
				} else {
					// don't update select cause we need closure to catch value
					// data is saved - we need to reload page
					window.location.reload();
				}
				return true;
			},
			failure: function(){
				alert("Server connection failed!");
			},
			error : function(){
				alert("Server error!");
			}
		});
	});
	
	/*
	 * Handle switch for making public registry
	 */
	jQuery('.eventtopcspublic input').click(function(){
		postData = { ProductListID : jQuery(this).attr('id'), status: jQuery(this).val() };
		jQuery.ajax({
			type: 'post',
			url: app.URLs.doPublic,
			data: postData,
			dataType: 'json',
			success: function(data) {
				if(!data || typeof(data.success) == 'undefined') {
					alert("Server error!");
					return false;
				}

				if (!data.success) {
					alert("Couldn't save information due to server errors");
					return false;
				} else {
					// data is saved - we need to reload page
					window.location.reload();
				}
				return true;
			},
			failure: function(){
				alert("Server connection failed!");
			},
			error : function(){
				alert("Server error!");
			}
		});
	});
	
	/*
	 * Handle switch for registry status
	 */
	jQuery('.eventtopcsstatus select').change(function(){
		postData = { ProductListID : jQuery('.eventtopcspublic input').attr('id'), status: jQuery(this).val() };
		jQuery.ajax({
			type: 'post',
			url: app.URLs.updateStatus,
			data: postData,
			dataType: 'json',
			success: function(data) {
				if(!data || typeof(data.success) == 'undefined') {
					alert("Server error!");
					return false;
				}

				if (!data.success) {
					alert("Couldn't save information due to server errors");
					return false;
				} else {
					// data is saved - we need to reload page
					window.location.reload();
				}
				return true;
			},
			failure: function(){
				alert("Server connection failed!");
			},
			error : function(){
				alert("Server error!");
			}
		});
	});

	/*
	 * Handle click for cancel button (delete registry item)
	 */
	jQuery('#cancelRegistry').click(function(){
		jQuery(jQuery(jQuery(this).attr('deleteName')).parent().parent().parent()).css('background-color', jQuery(this).attr('oldColor'));
		jQuery('#removefromregistrydialog').dialog('close');
	});

	/*
	 * Handle click for delete button (delete registry item)
	 */
	jQuery('#deleteRegistry').click(function(){
		jQuery(jQuery(this).attr('deleteName')).click();
	})
	/*
	 * Highlight the Registry Tab if on a Registry Page
	 */
	if(current_url.indexOf("GiftRegistry") !== -1){
		topsitenav.find("li a").each(function(){
			jQuery(this).removeClass("selected-context");
		});
		topsitenav.find("li.giggle-registry a").addClass("selected-context");
	}
});

