var AJAX_SPLITTER = "###"

function addDroppable(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.toQueryStringNoEncoding()
        return ajaxRequest(dragNDropUrl, false, link, false)
       } else {
       }
      }
  });
  }
}

function getUrl(url, isForm, pressedLink, asintraPageLink, ignoreFields) {

var ignore = true
if (ignoreFields != undefined) {
	ignore = ignoreFields
}
try {
	
	if (!isForm) {
		var params = url.substring(url.indexOf("?") + 1, url.length)
		if (params != "") {
			params += "&ajax=true"
		}
		if (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(pressedLink) + "=link"
		if (asintraPageLink) {
			params += "&ajaxIntraPage=true"
		}
	}

} catch(e) {
	alert(e)
}
	return $H({"url": url, "params" : params})
}


var isForm 
var pressedLink 
var openWindow 
var closeWindow 
var openWaitingWindow 
var asintraPageLink
var ajaxUrl
var onFailureCallBack
var sourcePage
var indicator
var showBeforeRequest
var modal = false
var autoResize = false

function ajaxRequest(url, options) {
	ajaxUrl = url
	isForm = options["isForm"]
	pressedLink =  options["pressedLink"]
	onFailureCallBack = options["onFailureCallBack"]
	openWindow = options["window"]
	closeWindow = options["closeWindow"]
	openWaitingWindow = options["waitingWindow"]
	sourcePage = options["sourcePage"]
	indicator =  options["indicator"]
	
	modal = false
	autoResize = false
	
	if (openWindow && openWindow["modal"]) {
		modal = openWindow["modal"]
	}
	if (openWindow && openWindow["autoResizing"]) {
		autoResize = openWindow["autoResizing"]
	}
	Window.keepMultiModalWindow=true
	asintraPageLink = false
	
	if (openWaitingWindow) {
		openInfoDialog();
	} else {
		makeRequest();
	}
	
	return false;
}

function openInfoDialog() { 
	Dialog.info(openWaitingWindow["message"], {className: openWaitingWindow["className"], width:openWaitingWindow["width"], height:openWaitingWindow["height"], showProgress: true}); 
	setTimeout(infoTimeout, openWaitingWindow["duration"]) 
} 

function infoTimeout() { 
	makeRequest()
} 

function changeCursor(useCursor) {
	document.body.style.cursor= useCursor;
}

function makeRequest() {
	changeCursor("wait")
	if (indicator) {
  	Element.show(indicator)
  }
	if($('ajaxNotification') && Ajax.activeRequestCount > 0) {
    	Effect.Fade('ajaxNotification',{duration: 0.25, queue: 'end'});
	}
	if (closeWindow && !openWindow) {
     asintraPageLink = true
	}
	try {
	var calculatedUrl = getUrl(ajaxUrl, isForm, pressedLink, asintraPageLink)
	url = calculatedUrl["url"]
	params = calculatedUrl["params"]
	} catch(e) {alert(e.message)}

	if (openWindow) {
		if (openWaitingWindow) {
			Dialog.closeInfo()
		}
		
		var win
		if (openWindow["showBeforeRequest"]) {
			win = Windows.getWindow(openWindow["windowId"] + "_window")
			if (win == null) {
				win = new Window(openWindow["windowId"] + "_window",  openWindow);
			}
			win.setHTMLContent("<div style='height:100%;vertical-align: middle' id='modal_dialog_progress' class='" + openWindow["className"] + "_progress'>  </div>") ;
			win.setConstraint(true, {left:10, right:10, top: 10, bottom:10})
			win.setDestroyOnClose(true)
			win.getContent().innerHTML.evalScripts()
			win.show()
			if (autoResize) {
				 var thatWin = win
				 setTimeout(function() {updateWindow(win, true)}, 50)
			} else {
				win.showCenter(modal)
			}
		}
		new Ajax.Request(url, {
		method: 'post', 'postBody': params ,
		onSuccess: function(request) {
				if (!request.responseXML || request.responseXML.getElementsByTagName('Page').length == 0) {
				 var content = request.responseText

				 if (closeWindow) {
				 		if (modal) {
				 			WindowUtilities.hideModal  = false
				 		}
						if (openWindow["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 (win == null) {
					 win = Windows.getWindow(openWindow["windowId"] + "_window")
					 
					 if (win == null) {
						 win = new Window(openWindow["windowId"] + "_window", openWindow);
						 newWindow = true
					 }
				 }

				 win.setHTMLContent(content) ;
				 win.setConstraint(true, {left:10, right:10, top: 10, bottom:10})
				 win.setDestroyOnClose(true)
				 win.getContent().innerHTML.evalScripts()
				 win.show()
				 win.visible= true
				 if (autoResize) {
				 		var thatWin = win
					 setTimeout(function() {updateWindow(win, modal & newWindow)}, 50)
				 } else {
				 		win.showCenter(modal & newWindow)
				 	
				 }
				} else {
					var responsePage = request.responseXML.getElementsByTagName('Page')[0].getAttribute("id")
					if (openWaitingWindow) {
						Dialog.closeInfo()
					}
					if ((closeWindow && responsePage != sourcePage) || (!closeWindow && responsePage != sourcePage) || ((openWindow && openWindow["showBeforeRequest"]) && responsePage == sourcePage)) {
						 WindowUtilities.hideModal =true
						 var window = Windows.getFocusedWindow()
						 if (window != null) { 
								window.close();
						} 
						computeRequest(request)
					} else {
						computeRequest(request)
						if (autoResize) {
							updateWindow(undefined, false)
						}
					}
				}
				changeCursor("default")
				if (indicator) {
            	Element.hide(indicator)
            }
			}, onFailure: function() {
			if($('ajaxNotification') && Ajax.activeRequestCount > 0) {
            	Effect.Appear('ajaxNotification',{duration: 0.25, queue: 'end'});	
            }
            if (onFailureCallBack && onFailureCallBack != "") {
            	eval(onFailureFunction + "()")
            }
            changeCursor("default")
            if (indicator) {
            	Element.hide(indicator)
            }
		}
		});
	} else {
		new Ajax.Request(url, {
		method: 'post', 'postBody': params ,
		onSuccess: function(request) {
				var responsePage = request.responseXML.getElementsByTagName('Page')[0].getAttribute("id")
				if (openWaitingWindow) {
					Dialog.closeInfo()
				}
				if ((closeWindow && responsePage != sourcePage) || (!closeWindow && responsePage != sourcePage) || ((openWindow && openWindow["showBeforeRequest"]) && responsePage == sourcePage)) {
						 WindowUtilities.hideModal =true
						 var window = Windows.getFocusedWindow()

						 if (window != null) { 
										window.close();
						} 
						
					}

						computeRequest(request)
						if (autoResize) {
							updateWindow(undefined, false)
						}
				
				changeCursor("default")
				if (indicator) {
            	Element.hide(indicator)
            }
			}, onFailure: function() {
			if($('ajaxNotification') && Ajax.activeRequestCount > 0) {
            	Effect.Appear('ajaxNotification',{duration: 0.25, queue: 'end'});	
            }
            if (onFailureCallBack && onFailureCallBack != "") {
            	eval(onFailureFunction + "()")
            }
            changeCursor("default")
            if (indicator) {
            	Element.hide(indicator)
            }
		}
		});
	}

}

function updateWindow(win, showModal) {
	if (win == undefined) {
		win = Windows.getFocusedWindow()
	}
	if (win != null) {
		 win.getSize()
		 win.updateWidth()
		 win.updateHeight()
		 win.showCenter(modal && showModal)
	}
}

function computeRequest(request) {

	var response = request.responseXML;

	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) {
		processElement(e)
	})
	var mainGrid = $A(page.getElementsByTagName('Grid')).find(function (c) {return (c.parentNode == page || c.parentNode.parentNode == page)})
	processElement(mainGrid)
	
}

function processElement(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(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 = AJAX_SPLITTER + "__" + id  + "__" + AJAX_SPLITTER
					var subContent = processElementContent(elem)
					htmlContent = htmlContent.replace(t, subContent)	
				} catch(e) {
					htmlContent = htmlContent.replace(t, "")	
				}
			} else {
				try {
					var t = AJAX_SPLITTER + "__" + id  + "__" + 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 = 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)
				}
		}		
	}
}

function processElementContent(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(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 = AJAX_SPLITTER + "__" + id  + "__" + AJAX_SPLITTER
						var subContent = processElementContent(elem)
						htmlContent = htmlContent.replace(t, subContent)	
					} catch(e) {
						htmlContent = htmlContent.replace(t, "")	
					}
				} else {
					try {
						var t = AJAX_SPLITTER + "__" + id  + "__" + 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 = processElementContent(e)
				var t = AJAX_SPLITTER + "__" + e.getAttribute("id")  + "__" + AJAX_SPLITTER
				htmlContent = htmlContent.replace(t, content)	
				
						htmlContent = htmlContent.replace(t, content)	
				
			});

			return htmlContent
		}
		
}