WRAjaxRequest = Class.create({
	url: null,
	requestUrl : null,
	requestParams : null,
	isForm : null,
	pressedLink : null,
	onFailureCallBack : null,
	openWindow : null,
	closeWindow : null,
	openWaitingWindow : null,
	sourcePage : null,
	indicator : null,
	modal : false,
	autoResize : false,
	asintraPageLink : false,
	indicator : null,
	win : null,
	request : null,
	
	initialize: function(url, options) {
		this.url = url
		this.isForm = options.get("isForm")
		this.pressedLink =  options.get("pressedLink")
		this.onFailureCallBack = options.get("onFailureCallBack")
		this.openWindow = options.get("window")
		this.closeWindow = options.get("closeWindow")
		this.openWaitingWindow = options.get("waitingWindow")
		this.sourcePage = options.get("sourcePage")
		this.indicator =  options.get("indicator")
	
		if (this.openWindow && this.openWindow.get("modal")) {
			this.modal = this.openWindow.get("modal")
		}
		if (this.openWindow && this.openWindow.get("autoResizing")) {
			this.autoResize = this.openWindow.get("autoResizing")
		}
		
		Window.keepMultiModalWindow=true
	},
	
	sendRequest : function() {
		if (this.openWaitingWindow) {
			this.openInfoDialog();
		} else {
			this._request();
		}
	},
	
	openInfoDialog : function() { 
		Dialog.info(this.openWaitingWindow.get("message"), {className: this.openWaitingWindow.get("className"), width: this.openWaitingWindow.get("width"), height: this.openWaitingWindow.get("height"), showProgress: true}); 
		setTimeout(this._request.bind(this), this.openWaitingWindow.get("duration")) 
	},

	_request : function() { 
		WRAjaxRequestUtils.changeCursor("wait")
		if (this.indicator) {
	  		Element.show(this.indicator)
	  	}
	  	
		if($('ajaxNotification') && Ajax.activeRequestCount > 0) {
	    	Effect.Fade('ajaxNotification',{duration: 0.25, queue: 'end'});
		}
		
		if (this.closeWindow && !this.openWindow) {
	    	this.asintraPageLink = true
		}
		
		try {
			var calculatedUrl = this.getUrl()
			this.requestUrl = calculatedUrl.get("url")
			this.requestParams = calculatedUrl.get("params")
		} catch(e) {alert(e.message)}
		
		if (this.openWindow) {
			var that = this;
			this.request = new WRAjaxRequestQueue.DTO(this.requestUrl, {
			 method: 'post', 'postBody': this.requestParams ,
			 onCreate: function(request) {
				Effect.Fade('ajaxNotification',{duration: 0.25, queue: 'end'});
				if (that.openWindow.get("showBeforeRequest")) {	
					try {
					   var response = "<div style='height:100%;vertical-align: middle' id='modal_dialog_progress' class='" + that.openWindow.get("className") + "_progress'>  </div>"
					   that.createAndPrepareWindow(response)
					} catch(e) {
						 that._onFailureCallback(e.message)
					}
				}
			 },
			 onSuccess: function(request) {
			 	var response = request.responseXML
			 	var responsePage = WRAjaxRequestUtils.getResponsePage(response)
				if (!response || !responsePage) {
				   response = request.responseText
				   try {
					  that.createAndPrepareWindow(response)
				   } catch(e) {
					  that._onFailureCallback(e.message)
				   }
				} else {
					try {
					  var response = request.responseXML
					  that.computeResponse(response)
					} catch(e) {
					  that._onFailureCallback(e.message)
					}
				}
			  }, onFailure: that._onFailureCallback
			});
		} else {
			var that = this;
			this.request = new WRAjaxRequestQueue.DTO(this.requestUrl, {
				 method: 'post', 'postBody': this.requestParams ,
				 onCreate: function() {
				 	Effect.Fade('ajaxNotification',{duration: 0.25, queue: 'end'});
				 },
				 onSuccess: function(request) {
						 try {
						   var response = request.responseXML
						   that.computeResponse(response)
						 } catch(e) {
							 that._onFailureCallback(e.message)
						 }
				 }, 
				 onFailure: that._onFailureCallback
			});
		}
		WRAjaxRequestUtils.addRequest(this.request)
		WRAjaxRequestUtils.startRequest()
		
		WRAjaxRequestUtils.changeCursor("default")
		if (this.indicator) {
	  		Element.show(this.indicator)
	  	}
	},
	
	createAndPrepareWindow : function(response) {
		if (this.openWaitingWindow) {
			Dialog.closeInfo()
		}
		
		if (this.closeWindow) {
			if (this.modal) {
				WindowUtilities.hideModal  = false
			}
			if (this.openWindow.get("showBeforeRequest")) {
				var window = Windows.windows[Windows.windows.length - 2]
				if (window != null) { 
					window.close();
					Windows.focusedWindow = win
				} 
			} else {
				var window = Windows.getFocusedWindow()
				if (window != null) { 
					window.close();
				} 
			}
		}
		var newWindow = false;
		if (this.win == null) {
			this.win = Windows.getWindow(this.openWindow.get("windowId") + "_window")
			
			if (this.win == null) {
				this.win = new Window(this.openWindow.get("windowId") + "_window", this.openWindow);
				newWindow = true
			}
		}
		if (this.openWindow.get("closable")) {
			 $(this.openWindow.get("windowId") + "_window_close").style.display=""
		}
		this.win.setHTMLContent(response) ;
		this.win.setConstraint(true, {left:10, right:10, top: 10, bottom:10})
		this.win.setDestroyOnClose(true)
		this.win.getContent().innerHTML.evalScripts()
		this.win.show()
		this.win.visible= true
		if (this.autoResize) {
			var that = this
			setTimeout(function() {that.updateWindowSize(that.win, that.modal & newWindow)}, 50)
		} else {
			this.win.showCenter(this.modal & newWindow)
		}
	},
	
	updateWindowSize : function(win, modal) {
		if (this.win == undefined) {
			this.win = Windows.getFocusedWindow()
		}
		if (this.win != null) {
			 this.win.getSize()
			 this.win.updateWidth()
			 this.win.updateHeight()
			 this.win.showCenter(this.modal && modal)
		}
	},
	
	computeResponse : function(response) {
		var responsePage = WRAjaxRequestUtils.getResponsePage(response)	  
		if (this.openWaitingWindow) {
			Dialog.closeInfo()
		}
		if ((this.closeWindow && responsePage != this.sourcePage) || (!this.closeWindow && responsePage != this.sourcePage) || ((this.openWindow && this.openWindow.get("showBeforeRequest")) && responsePage == this.sourcePage)) {
			WindowUtilities.hideModal = true
			var window = Windows.getFocusedWindow()
			if (window != null) {
				window.close();
			}
		}
		WRAjaxRequestUtils.computeRequest(response)
		
		if (this.autoResize) {
			this.updateWindowSize(undefined, false)
		}
		
		WRAjaxRequestUtils.changeCursor("default")
		if (this.indicator) {
			Element.hide(this.indicator)
		}
	},
	
	getUrl : function(ignoreFields) {
		var ignore = true
		var url = this.url
		if (ignoreFields != undefined) {
			ignore = ignoreFields
		}
		try {
			
			if (!this.isForm) {
				var params = url.substring(url.indexOf("?") + 1, url.length)
				if (params != "") {
					params += "&ajax=true"
				}
				if (this.asintraPageLink) {
					params += "&ajaxIntraPage=true"
				}
				var conditionInput = document.getElementById("conditions")
				params += "&" + conditionInput.name + "=" + encodeURIComponent(conditionInput.value)
				url = url.substring(0,url.indexOf("?")) 
			} else {
				var formName = url
				var url = "form" + formName.substring(0, formName.indexOf("FormBean")) + ".do"
		
				var FCKEditorFields = Form.getElements(formName).findAll(function (element) {
					return element.id.indexOf("___Config") >= 0
				});
				
				var formElements = Form.getElements(formName).findAll(function (element) {
					return element.type != "submit" && 
						element.type != "file" && 
						(!element.getAttribute("ignore") && element.getAttribute("ignore") != ignore) 
						&& !FCKEditorFields.any(function (field) { return element.name == field.id.substring(0, field.id.indexOf("___Config"))})
				});
				var params = Form.serializeElements(formElements)
				
			    try {
			        if(typeof(FCKeditorAPI) == "object") {
			          	FCKEditorFields.each(function(element) {
			    			var FCKEditorField = element.id.substring(0, element.id.indexOf("___Config"))
			    			var content = FCKeditorAPI.GetInstance(FCKEditorField).GetXHTML();
			    			params += "&" + encodeURIComponent(FCKEditorField) + "=" + encodeURIComponent(content) 
			    		})
			        }
			    } catch(err) {}
		  		
				
				params += "&ajax=true"
				params += "&" + encodeURIComponent(this.pressedLink) + "=link"
				if (this.asintraPageLink) {
					params += "&ajaxIntraPage=true"
				}
			}
		
		} catch(e) {
			alert(e)
		}
		return $H({"url": url, "params" : params})
	},
	
	_onFailureCallback : function(message) {
	  if($('ajaxNotification') && Ajax.activeRequestCount > 0) {
	  	  if (message) {
	  	  	$('ajaxNotification').innerHTML = message
	  	  }
		  Effect.Appear('ajaxNotification',{duration: 0.25, queue: 'end'});	
	  }
	  if (this.onFailureCallBack && this.onFailureCallBack != "") {
		  eval(this.onFailureFunction + "()")
	  }
	  WRAjaxRequestUtils.changeCursor("default")
	  if (this.indicator) {
		  Element.hide(indicator)
	  }
	}
});

var WRAjaxRequestUtils = {
	AJAX_SPLITTER : "###",
	requestsQueue : new WRAjaxRequestQueue(),
	
	addRequest : function(request) {
		this.requestsQueue.add(request)
	},
	
	startRequest : function() {
		this.requestsQueue.start()
	},
	
	changeCursor : function(cursor) {
		document.body.style.cursor= cursor;
	},
	
	getResponsePage : function(response) {
		if (response && response.getElementsByTagName('Page').length > 0) {
			return response.getElementsByTagName('Page')[0].getAttribute("id")
		}
		return null
	},
	
	computeRequest: function(response) {
	  var page = response.getElementsByTagName('Page')[0]
	  try {
		  var pageHiddenFields = page.getAttribute("id") + 'HiddenFields'
		  var hiddenFields = page.getElementsByTagName(pageHiddenFields)[0]
		  
		  if (hiddenFields) {
			  var hiddenFieldsContent = ""
			  var textNodes = $A(hiddenFields.childNodes)
			  textNodes.each(function (text) {
				  hiddenFieldsContent += text.nodeValue
			  });
			  Element.update($(pageHiddenFields),hiddenFieldsContent)
		  }
	  } catch (e) {
		  //alert(e.message)
	  }
	  
	  var customLocations = $A(page.getElementsByTagName('CustomLocation'))
	  customLocations.each(function (e) {
		  WRAjaxRequestUtils.processElement(e)
	  })
	  var mainGrid = $A(page.getElementsByTagName('Grid')).find(function (c) {return (c.parentNode == page || c.parentNode.parentNode == page)})
	  WRAjaxRequestUtils.processElement(mainGrid)
	
	},

	processElement : function(element) {
	  var content = $A(element.getElementsByTagName("Content")).find(function (c) {return c.parentNode== element})
	  var units = $A(element.getElementsByTagName("Units")).find(function (e) {return e.parentNode == element})
	  var cells = $A(element.getElementsByTagName("Cells")).find(function (e) {return e.parentNode == element}) 
	  var grids = $A(element.getElementsByTagName("Grids")).find	(function (e) {return e.parentNode == element})
	  var subPages = $A(element.getElementsByTagName("SubPages")).find	(function (e) {return e.parentNode == element})
	  
	  var htmlContent = ""
	  
	  var elements = $A()
	  if (units) {
		  elements = elements.concat($A(units.getElementsByTagName("Unit")).findAll(function (c) {return c.parentNode== units}))
	  }
	  if (cells) {
		  elements = elements.concat($A(cells.getElementsByTagName("Cell")).findAll(function (c) {return c.parentNode== cells}))
	  }
	  if (grids) {
		  elements = elements.concat($A(grids.getElementsByTagName("Grid")).findAll(function (c) {return c.parentNode== grids}))
	  }
	  if (subPages) {
		  elements = elements.concat($A(subPages.getElementsByTagName("SubPage")).findAll(function (c) {return c.parentNode== subPages}))  
	  }
	  if (content != null && ((element.getAttribute("changed") == "true") || (element.getAttribute("changedConditions") == "true"))) {
		  var textNodes = $A(content.childNodes)
		  textNodes.each(function (text) {
			  htmlContent += text.nodeValue
		  });
  
		  var splittedContent = $A(htmlContent.split(WRAjaxRequestUtils.AJAX_SPLITTER)).findAll(function(token) {return (token.startsWith("__") && token.endsWith("__"))})
  		
		  splittedContent.each(function (token) {
			  var id = token.substring(2, token.length - 2)
			  var elem = elements.find(function (e) {
				   return e.getAttribute("id") == id		
			  });
			  if (elem) {
					  try {
					  var t = WRAjaxRequestUtils.AJAX_SPLITTER + "__" + id  + "__" + WRAjaxRequestUtils.AJAX_SPLITTER
					  var subContent = WRAjaxRequestUtils.processElementContent(elem)
					  htmlContent = htmlContent.replace(t, subContent)	
				  } catch(e) {
					  htmlContent = htmlContent.replace(t, "")	
				  }
			  } else {
				  try {
					  var t = WRAjaxRequestUtils.AJAX_SPLITTER + "__" + id  + "__" + WRAjaxRequestUtils.AJAX_SPLITTER
					  var content = ""
					  var textNodes = $A(elem.childNodes)
					  textNodes.each(function (text) {
						  content += text.nodeValue
					  });
					  
					  htmlContent = htmlContent.replace(t, content)	
					  } catch(e) {
						  htmlContent = htmlContent.replace(t, "")
					  }
			  }
		  });
		  
		  if (element.nodeName == "CustomLocation") {
				  if (htmlContent) {
							  Element.update(element.getAttribute("id"), htmlContent)
						  } else {
							  Element.update(element.getAttribute("id"), "")
						  }
		  } else {
			  return htmlContent
		  }
		  
	  } else {
		  elements.each(function (e) {
				  var id = e.getAttribute("id")
				  var content = WRAjaxRequestUtils.processElement(e)
				  if (content == null && content != undefined) {
					  content = ""
					  var textNodes = $A(element.getElementsByTagName("Content")[0].childNodes)
					  textNodes.each(function (text) {
						  content += text.nodeValue
					  });
				  }
				  if(e.getAttribute("changed") == "true" || e.getAttribute("changedConditions") == "true" ) {
					  try {
						  if (content) {
							  Element.update($(id), content)
						  } else {
							  Element.update($(id), "")
						  }
					  } catch (e) {
						  //alert(id + " " + e.message)
					  }
				  }
		  });
		  if (element.nodeName == "Unit" || (element.nodeName == "CustomLocation" && element.getAttribute("computed") == "true") || (element.nodeName == "Cell" && element.getAttribute("computed") == "true")) {
			  var id = element.getAttribute("id")
				  content = ""
				  
				  var textNodes = $A(element.getElementsByTagName("Content")[0].childNodes)
				  textNodes.each(function (text) {
					  content += text.nodeValue
				  });
				  
				  try {
					  if (content) {
						  Element.update($(id), content)
					  } else {
						  Element.update($(id), "")
					  }
				  } catch (e) {
					  //alert(id + " " + e.message)
				  }
		  }	
	  }
	},

	processElementContent : function(element) {
	  var content = $A(element.getElementsByTagName("Content")).find(function (c) {return c.parentNode== element})
	  var units = $A(element.getElementsByTagName("Units")).find(function (e) {return e.parentNode == element})
	  var cells = $A(element.getElementsByTagName("Cells")).find(function (e) {return e.parentNode == element}) 
	  var grids = $A(element.getElementsByTagName("Grids")).find	(function (e) {return e.parentNode == element})
	  var subPages = $A(element.getElementsByTagName("SubPages")).find	(function (e) {return e.parentNode == element})
	  var htmlContent = ""
	  
	  var elements = $A()
	  if (units) {
		  elements = elements.concat($A(units.getElementsByTagName("Unit")).findAll(function (c) {return c.parentNode== units}))
	  }
	  if (cells) {
		  elements = elements.concat($A(cells.getElementsByTagName("Cell")).findAll(function (c) {return c.parentNode== cells}))
	  }
	  if (grids) {
		  elements = elements.concat($A(grids.getElementsByTagName("Grid")).findAll(function (c) {return c.parentNode== grids}))
	  }
	  if (subPages) {
		  elements = elements.concat($A(subPages.getElementsByTagName("SubPage")).findAll(function (c) {return c.parentNode== subPages}))  
	  }

	  if (content) {
		  var textNodes = $A(content.childNodes)
		  textNodes.each(function (text) {
			  htmlContent += text.nodeValue
		  });
		   
		  var splittedContent = $A(htmlContent.split(WRAjaxRequestUtils.AJAX_SPLITTER)).findAll(function(token) {return (token.startsWith("__") && token.endsWith("__"))})
		  
		  splittedContent.each(function (token) {
			  var id = token.substring(2, token.length - 2)
			  var elem = elements.find(function (e) {
				   return e.getAttribute("id") == id		
			  });
			  
			  
			  if (elem) {
				  try {
					  var t = WRAjaxRequestUtils.AJAX_SPLITTER + "__" + id  + "__" + WRAjaxRequestUtils.AJAX_SPLITTER
					  var subContent = WRAjaxRequestUtils.processElementContent(elem)
					  htmlContent = htmlContent.replace(t, subContent)	
				  } catch(e) {
					  htmlContent = htmlContent.replace(t, "")	
				  }
			  } else {
				  try {
					  var t = WRAjaxRequestUtils.AJAX_SPLITTER + "__" + id  + "__" + WRAjaxRequestUtils.AJAX_SPLITTER
					  var content = ""
					  var textNodes = $A(elem.childNodes)
					  textNodes.each(function (text) {
						  content += text.nodeValue
					  });
					  
					  htmlContent = htmlContent.replace(t, content)	
					  } catch(e) {
						  htmlContent = htmlContent.replace(t, "")
					  }
			  }
		  });

		  return htmlContent
	  } else {
		  elements.each(function (e) {
			  var content = WRAjaxRequestUtils.processElementContent(e)
			  var t = WRAjaxRequestUtils.AJAX_SPLITTER + "__" + e.getAttribute("id")  + "__" + WRAjaxRequestUtils.AJAX_SPLITTER
			  htmlContent = htmlContent.replace(t, content)	
			  htmlContent = htmlContent.replace(t, content)	
		  });

		  return htmlContent
	  }
		  
  },
  
  addDroppable: function(id, link, hoverClass) {
	if($(id)!=null){
		Droppables.drops = Droppables.drops.reject(function(d) {return d.element.id ==id });  
    	Droppables.add(id, {hoverclass: hoverClass, onDrop: function(element, droppableElement) {
			  var droppableUrl = droppableElement.getAttribute("url")
			  var droppableParams = droppableElement.getAttribute("params")
			  var draggableUrl = element.getAttribute("url")
			  var draggableParams = element.getAttribute("params")
				 
			  if (droppableUrl == draggableUrl) {
			   var queryString = new Hash()
			   queryString = queryString.merge(droppableParams.toQueryParams());
			   queryString = queryString.merge(draggableParams.toQueryParams());
			   var dragNDropUrl = droppableUrl + "?" + queryString.toQueryString(true)
			   return ajaxRequest(dragNDropUrl, $H({'pressedLink' : link}))
			  }
			}
  		});
  	}
  }
};