(function($) {

	
	
	$.fn.modaldialog = function(_config) {
		if(_config=="options") {
			var _options = getArg(arguments, 1);
		}

		return $(this).each(function() {
			var _self = $(this);
			
			if(_config=="options") {
				var _data = _self.data("options");
				_data = $.extend(_data, _options);
				_self.data("options", _data);
				
				return _data;
			}
			
			
			
			
			var defaults = {
				action: "click",			// String - action that shows the dialog
				anchor: "bl",				// String - where to anchor the dialog. bl = bottom-left, tr = top-right, rt = right-top, etc.
				append: $("body"),			// jQuery - where to append the HTML for the dialog
				bounce: false,				// Boolean - make the dialog bounce the first time it's shown?
				close_after_delay: false,	// Boolean|Integer - false or time in milliseonds after which to close the dialog
				close_on_blur: false,		// Boolean - this causes the dialog to close when the user /clicks/ outside of the dialog
				demanding: false,			// Boolean - will keep dialog open until _close(true) is called by the dialog itself and will prevent other dialogs from opening
				draggable: true,			// Boolean - make the dialog draggable?
				dialog: "generate",			// String - the ID of the dialog - "generate" will get a random id from the randomid() function
				elm: null,					// jQuery - reference to the dialog HTML
				left: -1,					// Integer - CSS "left" position
				live: false,				// Boolean - if true, dialog will be repositioned at "where" every time it is shown
				offset: [0,0],				// Array - this augments the top,left of the dialogs position
				onoff: false,				// Boolean - if true, dialog will close when the trigger is clicked a second time - only applies to click links (not hover)
				path: this.tagName.toLowerCase()=="form" ? _self.attr("action") : _self.attr("href"),	// String - where to get the dialog
				//path: this.tagName.toLowerCase()=="form" ? _self.attr("action") : this.getAttribute("href", 2),	// String - where to get the dialog
				show: true,					// Boolean - if true, the dialog will be shown as soon as it's loaded. False is essentially pre-caching the dialog
				show_screen: true,			// Boolean - shade the rest of the page (ie. true modal dialog)
				shown: false,				// Boolean - probably don't need to change this- modaldialog will set this to true after the first showing of the dialog
				top: -1,					// Integer - CSS "top" position
				where: false,				// jQuery - where to anchor the dialog
				
				start: function() {},		// Function - runs after dialog is fetched via ajax, but before positioned, displayed, etc.
				end: function() {},			// Function - runs after dialog is positioned, displayed, etc.
				onshow: function() {},		// Function - runs every time the dialog is shown
				onhide: function() {}		// Function - runs every time the dialog is hidden
			};
			
			var options = $.extend(defaults, _config);
			
			_self.data("options", options);
	
			var _dialog_positions = {
				set: function() {
					options.top  = options.elm.css("top");
					options.left = options.elm.css("left");
				},
				get: function() {
					if(options.where || options.live) {
						if(options.append.tagName()=="body") {
							var _position = options.where.offset();
						} else {
							var _position = options.where.position();
						}
						
						var _offset_top  = options.offset[0];
						var _offset_left = options.offset[1];
						
						var _top = 0;
						var _left = 0;
						
						var _position_dialog = function(_type) {
							switch(_type) {
								case "lt":
									_offset_left += options.where.width() + (parseInt(options.elm.find(".dagger:first").css("width"), 10) || 0);
								break;
								case "lc":
									_offset_top += options.elm.height() / 3;
									_offset_left += options.where.width() + (parseInt(options.elm.find(".dagger:first").css("width"), 10) || 0);
								break;
								case "rt":
									_offset_left -= options.where.width() + (parseInt(options.elm.find(".dagger:first").css("width"), 10) || 0) + options.elm.width();
								break;
								case "bl":
									_offset_top += options.elm.height() + (parseInt(options.elm.find(".dagger:first").css("height"), 10) || 0);
								break;
								case "bc":
									_offset_top += options.elm.height() + (parseInt(options.elm.find(".dagger:first").css("height"), 10) || 0);
									_offset_left -= (options.elm.width() / 2) - (options.where.width() / 2);
								break;
							}
							
							if(options.where.parents("#pcart").size()>0) {
								var _parent_carousel = options.where.parents(".carousel-list");
								_offset_left += parseInt(_parent_carousel.css("left"), 10) || 0;
							} else if(options.append.tagName()!="body") {
								var _parents = options.where.offsetParent();
								_offset_left += _parents.offset().left;
								_offset_top += _parents.offset().top;
							}
							
							_top  = _position.top  - _offset_top;
							_left = _position.left + _offset_left;
						}
						
						_position_dialog(options.anchor);
						if(options.anchor=="lt") {
							var _elm_left = _left + options.elm.width() - 140;
							if(_elm_left > $(".wrapper").width()) {
								options.elm.replaceClass("dialog-align-lt", "dialog-align-rt");
								
								_position_dialog("rt");
							}
						}
												
						options.top  = _top;
						options.left = _left;
					} else if(options.top==-1) {
						var _left = ($(window).width() / 2) - (options.elm.width() / 2) + options.offset[1];
						var _top = ($(window).height() / 2) - (options.elm.height() / 2) + options.offset[0];
						options.top  = _top;
						options.left = _left;
					}
				}
			};
			
			var _close_all = function() {
				var _dialogs = _global_config.dialogs;
				for(var i=0; i<_dialogs.length; i++) {
					_close(true, _dialogs[i].elm);
				}
			};
			
			var _show_screen = function() {
				$("#screen").show();
			};
			
			var _hide_screen = function() {
				$("#screen").hide();
			};
			
			var _close = function() {
				var _elm = getArg(arguments, 1, options.elm);
				var _force = getArg(arguments, 0, false);
				
				if(_force) { _hide(_elm); return; }
				
				later(function() {
					if(!_elm.hasClass("hovering")) {
						_hide(_elm);
					}
				}, 300);
			};
			
			var _hide = function() {
				var _elm = getArg(arguments, 0, options.elm);
				
				var _object = _elm.find("object");
				var _embed = _elm.find("embed");
				if(_object.size()>0 || _embed.size()>0) {
					if(_embed.size()>0) {
						_object = _embed;
					}
					var _clone = _object.clone();
					var _parent = _object.parent();
					_object.remove();
					_clone.appendTo(_parent);
				}
				
				_elm.hide();
				options.onhide(options.elm);
			};
			
			var _show = function() {
				//log(_global_config.demanding_dialog_open);
				if($(".dialog-message.demanding-dialog:visible").size()==0) {
					if(_self.hasClass("close-this-dialog")) {
						_close(true, _self.parents(".modal-dialog"));
					}
					if(options.show_screen) { _show_screen(); }
					if(options.live) {
						_dialog_positions.get();
						options.elm.css("left", options.left);
						options.elm.css("top", options.top);
					}
					options.elm.show();
					options.onshow(options.elm);
					if(options.close_on_blur) {
						hideOnBlur(options.elm, function() {
							_hide();
						});
					}
					if(options.demanding) {
						options.elm.addClass("demanding-dialog");
					}
				}
			};
			
			
			
			var _open = function() {
				if(!options.elm.hasClass("positioned")) {
					_dialog_positions.get();
					//log(_current);
					
					var _dialog = options.elm;
					
					if(options.bounce) {
						_dialog.css("left", options.left);
						_dialog.css("top", options.top - 20);
						_show();
						var _end = options.top;
						_dialog.animate(  {top:_end}, 100 )
							  	.animate( {top:_end-=5}, 100 )
							  	.animate( {top:_end+=5}, 100 );
					} else {
						_dialog.css("left", options.left);
						_dialog.css("top", options.top);
						_show();
					}
					
					if(options.close_after_delay) {
						later(function() {
							options.elm.hide();
						}, options.close_after_delay);
					}
	
					_dialog_positions.set();
				}
				if(options.draggable) {
					_dialog.draggable({
						stop: function(event, ui) {
							_dialog_positions.set(_dialog);
						},
						cancel: ".buttons, label, input, select, textarea, .form-element, object, embed"
					});
				}
				options.shown = true;
			};
			
			var setupClose = function(action) {
				options.elm.find(action).click(function() {
					if(action != ".close-this-dialog") {
						_hide_screen();
					}
					_hide();
					return false;
				});
			};
			
			var _setupDialogHover = function() {
				options.elm.hover(
					function() {
						options.elm.addClass("hovering");
					},
					function() {
						options.elm.removeClass("hovering");
						if(options.action=="hover") {
							_close(true);
						}
					}
				);
			};
			
			var _setupTrigger = function() {
				if(options.action=="click") {
					_self.unbind('click');
					_self.click(function() {
						if(options.onoff && options.elm.is(":visible")) {
							_hide();
						} else {
							_show();
						}
						return false;
					});
				} else if(options.action=="hover") {
					_self.hover(
						function() {
							options.elm.addClass("hovering");
							if(!options.shown) {
								_open();
							} else {
								_show();
							}
						},
						function() {
							options.elm.removeClass("hovering");
							_close();
						}
					);
				}
			};
			
			
			
			var _setup = function() {
				
				
				$("body").css("cursor", "default");
				var _reuse = getArg(arguments, 0, false);
				if(!_reuse) {
					options.start(options.elm);
				
					_setupDialogHover();
				}
				_setupTrigger();
				
				if(options.show) { _open(); }
				
				if(!_reuse) {
					
					//added by jesty
					setupSignIn(options.elm);
					setupForgotPass();
					setupSignUp(options.elm);
				  //added by Jesty 
						
					//addedd by Shah
					//changePassword(options.elm);
					//addedd by Shah
			//added by william
					setupFeedback();
					setupOutOfStock(options.elm);
					setupListsOutOfStock(options.elm);
			//end added by william		
					setupClose(".cancel");
					options.elm.find(".open-modal-dialog").modaldialog();
					options.elm.find("input:first").focus();
				
					options.end(options.elm);
				}
			};
			
			
			
			
			//added by Jesty
	/*
			var setupSignIn = function(){
				
			options.elm.find('#form-signin').submit(function() {
				
					var errorBlock = options.elm.find('#error');
					var usernameValue = options.elm.find("#username").attr("value");
					
				  var URLtosubmit = "";
				  //alert(this);
				  if (options.elm.find('#username').val() == "")
					{
			      	errorBlock.text("Please enter a valid Userid !").show();
			      	return false;
        	}
        	else if (options.elm.find('#password').val() == "")
					{
							errorBlock.text("Please enter a valid Password !").show();
							return false;
					}
					else 
					{
							if( (options.elm.find("#username").val().length < 5) 
        				||(usernameValue.indexOf(' ') > 0) 
								||(usernameValue.indexOf('@') < 1) 
								||(usernameValue.lastIndexOf('.') < (usernameValue.indexOf('@') + 2) ) 
								||(usernameValue.lastIndexOf('.') >= ((options.elm.find("#username").val().length) - 2) ) 
								)
						{
							errorBlock.text("Please enter a valid email Address * !").show();
						}
						else
						{	
					   	URLtosubmit = options.elm.find('#form-signin').attr('action');
							 var username = "";
							  $.post(URLtosubmit, {"mode":"signin", "user": options.elm.find("#username").val() , "pass": options.elm.find("#password").val() },
							   function(data){
							   	//do check, if SIGN in and user is valid run both line below
							   	
							   	if (data.status == "valid")
							   	{
							 
							   		//$('#reg li:nth-child(1)').text("Hello "+data.firstname ); 
							  		$('#reg li:nth-child(1)').html("<a href='"+ data.myaccounturl +"'>Hello "+ data.firstname  + "</a>");
							  		$('#reg li:nth-child(2)').html("<a href='"+ URLtosubmit +"' id='signout' class='open-modal-dialog' >Sign out</a>");
							  		
							  		setupLogout();
							  			if(options.elm.find("#remember:checked").length == 1)
							  			{
							  				setCookie("firstname",data.firstname,60);
							  			}
							  		//put valid links for Wishlist, giftlist and Recipe box here 
							  		$("#login").hide();
										$("#screen").hide();	
										//location.reload();	
										
										$.get("/cs/Satellite?pagename=PotsAndPans%2FPersistentCart", function(data) {
											
										//alert(data.count);
										$("#pcart").replaceWith(data);
										//$("#pcart").html(data);
										//$(".empty").hide();
										//_pcart.setupexistingcart();
										_pcart = setupPCart();
										//$('.dagger').attr('id').html(data); 
										//location.reload();
										});
										var _item = $(this).parents(".cart");
										var _count = _item.find("span.count").text();
										//alert(_count);
										//_pcart = setupPCart();
										//location.reload();
										//$.get("",function(){
												//get response from load cart
												//$("you cart div").html("Data back from GET");
										//})
									}
									else
									{
											options.elm.find('#error').text("Please enter a valid Userid and password !").show();
											options.elm.find("#username").val("");
											options.elm.find("#password").val("");
											return false;			
									}	
							   }, "json");
					}
				 }
				  return false;
				});
			
				
				};
		
	   	//added by Jesty
			var setupSignUp = function(){
			options.elm.find('#form-reg').submit(function() {
				
				var username = options.elm.find("#username");
				var usernameValue = username.attr("value");
				var errorBlock = options.elm.find('#error');
				
				if (options.elm.find("#default-form-name-first-name").val() == "")
				{
					errorBlock.text("Please enter a First name").show();
			   	return false;
				}
				else if (options.elm.find("#default-form-name-last-name").val() == "")
				{
					errorBlock.text("Please enter a Last name").show();
			    return false;
				}
				else if( (username.val().length < 5) 
        				||(usernameValue.indexOf(' ') > 0) 
								||(usernameValue.indexOf('@') < 1) 
								||(usernameValue.lastIndexOf('.') < (usernameValue.indexOf('@') + 2) ) 
								||(usernameValue.lastIndexOf('.') >= ((username.val().length) - 2) ) 
								)
				{
							errorBlock.text("Please enter a valid Email Address !").show();
			      	return false;
				}
				else if (options.elm.find("#password").val() == "")
				{
							errorBlock.text("Please enter a valid Password").show();
			      	return false;
				}	
				else if (options.elm.find("#password").val().length < 6)
				{
							errorBlock.text("Please enter a Password at least 6 char long").show();
			      	return false;
				}
				else if (options.elm.find("#password-confirm").val() =="")
				{
						  errorBlock.text("Please confirm the Password").show();
			      	return false;
				}
				else if (options.elm.find("#password").val() != options.elm.find("#password-confirm").val())	
				{
							errorBlock.text("Password field should match Confirm Password").show();
			      	return false;
				}
				else if ( options.elm.find("#terms-agree:checked").length != 1)
				{
							errorBlock.text("Please read and agree to Terms and Conditions").show();
			      	return false;
				}
				else
				{
				 $.post(options.elm.find('#form-reg').attr('action'), {"mode":"signup", "firstname": options.elm.find("#default-form-name-first-name").val() , "lastname": options.elm.find("#default-form-name-last-name").val(),
				 	"username": options.elm.find("#username").val() , "URLtosubmit": options.elm.find("#URLtosubmit").val(), "Password": options.elm.find("#password").val() , "Passwordconf": options.elm.find("#password-confirm").val() ,
				 	"termsagree": options.elm.find("#terms-agree:checked").length , "marketingoptin": options.elm.find("#marketing-opt-in:checked").length },
							   function(data){
							   	
							   	//alert(data.firstname + ":" + data.lastname + ":" + data.username + ":" + data.Password + ":" + data.Passwordconf + ":" + data.termsagree + ":" + 
							   	//data.marketingoptin );	
							   	
							   	if (data.status =="valid")
							   	{
							   		
							   		//$('#reg li:nth-child(1)').text("Hello "+data.firstname ); 
							  		$('#reg li:nth-child(1)').html("<a href='"+ data.myaccounturl +"'>Hello "+ data.firstname  + "</a>");
							  		$('#reg li:nth-child(2)').html("<a href='"+ data.URLtosubmit +"' id='signout' class='open-modal-dialog' >Sign out</a>");
							  		setupLogout();
							  		$("#register").hide();
										$("#screen").hide();  			
							   	}
							   	else
							   	{
							   			alert("here");
							   			errorBlock.text(data.error).show();
							   			return false;
							   	}
							   	
							   	
							   	
							   }, "json");
				}
							  
							  return false;
							   
				  
				});
			
				//return false;
				};	
			
		*/		
			
				
		//added by jesty
		var setupForgotPass = function() {
			options.elm.find('#forgotPass').submit(function() {
					$.post(options.elm.find('#forgotPass').attr('action'), {"username":options.elm.find("#forgotPass #username").val()},
					   function(data){
					  	if (data.status == "notvalid")
					  	{
					  			options.elm.find('#forgotPass #error').text("Please enter a valid Userid!").show();
					  			return false;
					  	}
							else
							{
								//$.get("/cs/Satellite?pagename=PotsAndPans%2FModalDialog&path=pagename%3DPotsAndPans%2FForgotPasswordConfirmation%26site%3DPotsAndPans", {}, function(data) {
							//alert(data);
						//	options.elm.find('#forgotten-confirm #error').text("text here").show();
					  //			return false;
					//$("#forgotten").hide();
					//$("#screen").hide();	
					
					//$.get("/cs/Satellite?pagename=PotsAndPans%2FModalDialog&path=pagename%3DPotsAndPans%2FForgotPasswordConfirmation%26site%3DPotsAndPan", {}, function(data) {
					//});
				//	alert(data.confirmationURL);
					
			$.post("/cs/Satellite?pagename=PotsAndPans%2FModalDialog&path=pagename%3DPotsAndPans%2FForgotPasswordConfirmation%26site%3DPotsAndPans", function(data) {
					
								//$("#forgotten").hide();
							//	$("#screen").hide();	
								//var _parent = $(this).parents("#forgotten-confirm");
								//alert(_parent);
								//$('#forgotten').detach();
								//$('#forgotten-confirm');
								$("#forgotten").html(data).show();
								setupClose(".cancel");
								//$("#forgotten").replaceWith(data);
								
							//	$(data).show();
							//	_pcart.setup();
							//	$(data);
							//		$("#forgotPass").show();
							//		$("#screen").show();
							//	$("#forgotPass #error").html(data);
					  	//	return false;
							//	options.elm.find('#forgotten').html(data).show();
					 			return false;
								});
							
							//$("#forgotten").modaldialog({
							//	path: "?pagename=PotsAndPans/ForgotPasswordConfirmation&site=PotsAndPans",
							//	draggable: true,
						//	});
							
							
							
						
							}  			
			 			}
					   	, "json");
					return false;				
				});	
		}; 
//added by wm
var setupFeedback = function(){
		var path = getArg(arguments, 0, options.elm);
		//path.find('#form-feedback').unbind("submit");
		//alert("after unbind");
		path.find('#form-feedback').submit(function() {
			var errorBlock = path.find('#error');
			var ratingVal = "";
			//alert("setupfeedback");
				//alert("radioval checked: "+$('input:radio[name=rating]:checked').val());
				if (($('input:radio[name=rating]:checked').val() == "")||($('input:radio[name=rating]:checked').val() == null))
				{
					errorBlock.text("Please select a rating.").show();
			   	return false;
				}
				else if (path.find("#do-better").val() == "")
				{
					errorBlock.text("Please enter text in the field").show();
			    return false;
				}
				else
				{
					//alert("no error");
					ratingVal = $('input:radio[name=rating]:checked').val();
					//alert("ratingVal:"+ratingVal);
					var feedbackdata = {"feedbackRating": ratingVal, "feedbackDoBetter": path.find("#do-better").val() , "feedbackComments": path.find("#comments").val()};
					//alert("feedbackdata.feedbackRating:"+feedbackdata.feedbackRating);
					errorBlock.text("").hide();
				 $.post(path.find('#form-feedback').attr('action'), {"feedbackRating": ratingVal, "feedbackDoBetter": path.find("#do-better").val() , "feedbackComments": path.find("#comments").val(), "confirm":"1"},
							   function(data){
										//alert(data);
										//alert(path)
										path.html($(data).html());
										//alert("try to close");
										setupClose(".cancel");
							   });
				}		  
							  return false;
				});
			
				//return false;
				};	
//end added by wm

					
			var init = function() {
				//log("#"+options.dialog);
				$("body").css("cursor", "progress");
				if($("#"+options.dialog).size()>0) {
					//alert("bla");
					options.elm = $("#"+options.dialog);
					_setup(true);
				} else {			
					//$.get( options.path, function(data) {
					$.get("/cs/Satellite?pagename=PotsAndPans%2FModalDialog", {path: options.path.split("?")[1]}, function(data) {
						options.elm = $(data).appendTo(options.append);
						_setup();
					});
				}
			};
			
			
			
			
			if(_self.tagName()=='form') {
				_self.submit(function() {
					init();
					return false;
				});
			} else {
				if(options.action=="hover" || options.action=="temp") {
					init();
				} else {
					_self.unbind('click');
					_self.click(function() {
						init();
						return false;
					});
				}
			}
			
		});
	};
})(jQuery);

