
Gallery = {
	
	// the contextPath initialized with default value
	contextPath : '/',
	
	// An array used to store current offset values.
	offset : new Array(),
	
	// An array used to store current perPage values.
	perPage : new Array(),

	// An array used to store onSuccess, onError and other callbacks. 
	galleryСallbacks : new Array(),
	
	// An array contains the names of forms waiting for server responce on submit request.
	pendingSubmitRequests : new Array(),

	selectDisplayName : function(itype) {
		var dispId = "display" + capitalize(itype);
		if (typeof document.getElementById(dispId) == "undefined") {
			dispId = "displayItems";
		}
		return dispId;
	},
	
	displayItems : function(data, itype, dispId) {
		if (data == "") {
			return;
		}
		var disp;
		if ((typeof dispId != "undefined") &&  (dispId != "")) {
			disp = document.getElementById(dispId);
		} else {
			disp = document.getElementById(selectDisplayName(itype));	
		}
		if (typeof disp != "undefined") {		
			disp.style.visibility = 'visible';
		    disp.style.display = 'block';
		    disp.innerHTML = data;
		    
			var browserType;
			if (document.layers) {browserType = "nn4"}
			if (document.all) {browserType = "ie"}
			if (window.navigator.userAgent.toLowerCase().match("gecko")) {
			   browserType= "gecko"
			}		
			
		var x;
			if (browserType != "ie") {
				x = disp.getElementsByTagName("script"); 
			} else {
				var x = new Array();
			    var idx = data.indexOf('<script');
			    var i = 0;
			    while ( idx > -1 ) {
			        idx = data.indexOf('>', idx) + 1;		        
			        var idx2 = data.indexOf('</script>', idx);		        
			        x[i] = new Object();
			        var res = data.substring(idx, idx2);
			        res = res.replace("<!--", "");
					res = res.replace("-->", "");
			        x[i].text = res;
			        idx = data.indexOf('<script', idx2);
			        i++;
			    }					
			}
		    // exec the javascript
			for(var i=0;i<x.length;i++) {
				eval(x[i].text);
			}
		} else {
			// developers error
			alert('Ошибка :(');
		}
	},

	initListValues : function(itype, pp) {	
		if (typeof pp != "undefined") {
			Gallery.perPage[itype] = pp;	
		}
		if (typeof this.offset[itype] == "undefined") {
			Gallery.offset[itype] = 0;
		}
	},
	
	loadItems : function(itype, reqUri, dispId, pp, contextPath, notShowProgress) {
		if (typeof contextPath != "undefined") {
			Gallery.contextPath = contextPath;
		}
		Gallery.initListValues(itype, pp);
		
		Gallery.invokeOnBeforeActionHandlers('loadItems', itype, dispId);
		
		var url = reqUri;
		if (typeof Gallery.contextPath != "undefined"){
			url = Gallery.contextPath + url;
		}	
		AjaxRequest.post({'url':url,
			'parameters':{
							'action': 'showlist',
							'itype': itype,
							'offset': Gallery.offset[itype],
							'perPage': Gallery.perPage[itype]
						 },
			"onSuccess":			
				function (req) {
						data = req.responseText;
						if (data == "error") {
							Gallery.invokeOnErrorHandlers('loadItems', itype);
						} else {
							Gallery.invokeOnSuccessHandlers('loadItems', itype, data);
							Gallery.displayItems(data, itype, dispId);
							Gallery.invokeOnAfterActionHandlers('loadItems', itype, data);
						}	
				}, 
			"onLoading":function() { 
				if (notShowProgress == null) { 
					showLoadingProgress(document.getElementById("defaultDisplayElement")); 
				} 
			},
			"onComplete": function() { 
				if (notShowProgress == null) { 
					hideLoadingProgress(); 
				}
			},
			"onError": function (req) { 
				hideLoadingProgress(); 
				if (notShowProgress == null) { 
					alert("Ошибка...");	
				}				
			}
		});	
	},
		
	submitSearch : function(formName, itype, dispId, pp, contextPath) {
		Gallery.invokeOnBeforeActionHandlers('submitSearch', itype, dispId, pp, contextPath)
		Gallery.offset[itype] = 0;
		Gallery.savedForm = cloneAForm(formName);
		Gallery.submitViaAjax(formName, itype, dispId, pp, contextPath);
		return false;
	},
	
	submitViaAjax : function(formName, itype, dispId, pp, contextPath, notShowProgress) {
		if (typeof document.forms[formName] != "undefined") {
			if (!Gallery.canSubmitForm(formName)) {
				return;
			}
			Gallery.addPendingSubmitRequest(formName);
			if (Gallery.savedForm == null) {
				Gallery.savedForm = cloneAForm(formName);
			}
			Gallery.initListValues(itype, pp);
			Gallery.invokeOnBeforeActionHandlers('submitViaAjax', itype, dispId);
			AjaxRequest.submit(
		    	Gallery.savedForm, {		
		    		'onSuccess':function (req) {
						try {
							data = req.responseText;
							if (data == "error") {
								Gallery.invokeOnErrorHandlers('submitViaAjax', itype);
							} else {
								Gallery.invokeOnSuccessHandlers('submitViaAjax', itype, data);
								Gallery.displayItems(data, itype, dispId);
								Gallery.invokeOnAfterActionHandlers('submitViaAjax', itype, data);
							}
							Gallery.removePendingSubmitRequest(formName);
						} catch(e) {
							Gallery.removePendingSubmitRequest(formName);
						}
					},
					'offset': Gallery.offset[itype],
					'perPage': Gallery.perPage[itype],
					'action':'showlist',
					'itype':itype,	
					"onLoading":function() { 
						if (notShowProgress == null) {
							showLoadingProgress(document.getElementById("defaultDisplayElement"));
						} 
					},
					"onComplete": function() { 
						if (notShowProgress == null) {
							hideLoadingProgress();
						} 
					},
					"onError": function (req) { 
						Gallery.removePendingSubmitRequest(formName);
						hideLoadingProgress(); 
						if (notShowProgress == null) { 
							alert("Ошибка...");
						}
					}
		    	}
		    );
		} else {
			// developers error
			alert("Ошибка :(");
		}
	},
		
	onChangeSelect : function(itype, reqUri, dispId, contextPath) {
		var newPerPage = parseInt(document.getElementById("perPage").value);
		Gallery.offset[itype] = 0;
		Gallery.loadItems(itype, reqUri, dispId, newPerPage, contextPath);
	},
		
	deleteItem : function(itype, reqUri, itemId, dispId, perPage, contextPath) {
		if (confirm("Вы уверены?")) {
			if (typeof contextPath != "undefined") {
				Gallery.contextPath = contextPath;
			}
			Gallery.initListValues(itype, perPage);
		
			var url = reqUri;
			if (typeof Gallery.contextPath != "undefined"){
				url = Gallery.contextPath + url;
			}	
			Gallery.invokeOnBeforeActionHandlers('deleteItem', itype, reqUri, itemId)
			
			AjaxRequest.post({
				'url':url,
				'parameters':{
								'itype':itype,
								'itemId':itemId,
								'action':'delete'
							 },
				"onSuccess":			
					function (req) {
						var response = req.responseText;
						if (response != "error") {
							Gallery.invokeOnSuccessHandlers('deleteItem', itype, reqUri, dispId);
						} else {
							Gallery.invokeOnErrorHandlers('deleteItem', itype, reqUri, dispId);
						}
					},
				"onLoading":function() { showLoadingProgress(document.getElementById("defaultDisplayElement")); },
				"onComplete": function() { hideLoadingProgress(); },
				"onError": function (req) { 
					hideLoadingProgress(); 
					alert("Ошибка...");	
				}			
			});
		}
		return false;	
	},
			
	sendActionRequest : function(actionForm, itype, reqUri, dispId, pp, contextPath) {
		if (!Gallery.canSubmitForm(actionForm.name)) {
			return false;
		}
		Gallery.addPendingSubmitRequest(actionForm.name);
		if (typeof contextPath != "undefined") {
			Gallery.contextPath = contextPath;
		}
		Gallery.invokeOnBeforeActionHandlers('sendActionRequest', itype, dispId)
		AjaxRequest.submit(
	    	document.forms[actionForm], {		
	    		'onSuccess':function (req) {
					try {
	 					var response = req.responseText;
						if (response != "error") {
							Gallery.invokeOnSuccessHandlers('sendActionRequest', itype, response, actionForm);
							Gallery.loadItems(itype, reqUri, dispId, pp, contextPath);
						} else {
							Gallery.invokeOnErrorHandlers('sendActionRequest', itype, actionForm);
						}
 						Gallery.removePendingSubmitRequest(actionForm.name);
					} catch(e) {
						Gallery.removePendingSubmitRequest(actionForm.name);
					}
				},
				"onLoading":function() { showLoadingProgress(document.getElementById("defaultDisplayElement")); },
				"onComplete": function() { hideLoadingProgress(); },
				"onError": function (req) { 
					Gallery.removePendingSubmitRequest(actionForm.name);
					hideLoadingProgress(); 
					alert("Ошибка...");	
				}			
	    	}
	    );		
	   	return false;
	},		
			
	sendSubmitRequest : function(actionForm, formName, itype, dispId, pp, contextPath) {
		if (typeof contextPath != "undefined") {
			Gallery.contextPath = contextPath;
		}
		Gallery.invokeOnBeforeActionHandlers('sendSubmitRequest', itype, dispId)
		
		AjaxRequest.submit(
	    	document.forms[actionForm], {		
	    		'onSuccess':function (req) {
					var response = req.responseText;
					if (response != "error") {
						Gallery.invokeOnSuccessHandlers('sendSubmitRequest', itype, response, actionForm);
						Gallery.submitViaAjax(formName, itype, dispId, pp, contextPath);
					} else {
						Gallery.invokeOnErrorHandlers('sendSubmitRequest', itype);				
					}
				},
				"onLoading":function() { showLoadingProgress(document.getElementById("defaultDisplayElement")); },
				"onComplete": function() { hideLoadingProgress(); },
				"onError": function (req) { 
					hideLoadingProgress(); 
					alert("Ошибка...");	
				}			
	    	}
	    );
	   	return false;    
	},

	markAll : function(firstMarkAll, secondMarkAll, itype, perPage){
		Gallery.initListValues(itype, perPage);
		
		var mainBox = document.getElementById('markAll');
		if (firstMarkAll != null) {
			mainBox = document.getElementById(firstMarkAll);
		}
		if (mainBox != null) {
			mainBox.checked=mainBox.checked? 1:0;
			for (var i=Gallery.offset[itype]; i<=(perPage+Gallery.offset[itype]); i++) {
		 		var box = document.getElementById('checkBox_' + i);
				if (box != null) {
				 	box.checked=mainBox.checked;
				}
			}
		}
		if (secondMarkAll != null) {
			document.getElementById(secondMarkAll).checked=mainBox.checked;
		}
	},

	performAction : function(action, itype, reqUri, contextPath, confirmMsg) {
		if (confirmMsg != null) {
			if(!confirm(confirmMsg)) {
				return false;
			}
		}
		if (typeof contextPath != "undefined") {
			Gallery.contextPath = contextPath;
		}
		//Gallery.initListValues(itype, perPage);
		var url = reqUri;
		if (typeof Gallery.contextPath != "undefined"){
			url = Gallery.contextPath + url;
		}	
		AjaxRequest.post({
			'url':url,
			'parameters':{
							'itype':itype,
							'action':action
						 },
			"onSuccess":			
				function (req) {
					var response = req.responseText;
					if (response != "error") {
						Gallery.invokeOnSuccessHandlers('performAction', action, itype, reqUri, response);
					} else {
						Gallery.invokeOnErrorHandlers('performAction', action, itype, reqUri);
					}
				},
			"onLoading":function() { showLoadingProgress(document.getElementById("defaultDisplayElement")); },
			"onComplete": function() { hideLoadingProgress(); },
			"onError": function (req) { 
				hideLoadingProgress(); 
				alert("Ошибка...");	
			}			
		});
		return false;	
	},

	loadSimpleContent : function(reqUri, dispId, contextPath) {
		if (typeof contextPath != "undefined") {
			Gallery.contextPath = contextPath;
		}
		var url = reqUri;
		if (typeof Gallery.contextPath != "undefined"){
			url = Gallery.contextPath + url;
		}	
		AjaxRequest.post({
			'url':url,
			'parameters':{},
			"onSuccess":			
				function (req) {
					var data = req.responseText;
					Gallery.displayItems(data, 'default', dispId);
					Gallery.invokeOnAfterActionHandlers('loadSimpleContent', reqUri, dispId, contextPath);
				},
			"onLoading":function() { 
				showLoadingProgress(document.getElementById("defaultDisplayElement"));
			},
			"onComplete": function() { 
				hideLoadingProgress(); 
			},
			"onError": function (req) { 
				hideLoadingProgress(); 
				alert("Ошибка...");	
			}			
		});
		return false;	
	},

	setOffsetToLastPage : function(itype, perPage, total) {
		Gallery.offset[itype] = Math.floor(total/perPage) * perPage;
	},
		
	addOnSuccessHandler : function(galleryFuncName, callback) {
		Gallery.registerCallback(galleryFuncName + "OnSuccessHandler", callback);
		return callback;
	},	
		
	invokeOnSuccessHandlers : function(galleryFuncName) {
		arguments[0] = galleryFuncName + "OnSuccessHandler";
		Gallery.invokeCallbacks.apply(this, arguments);
	},
	
	addOnErrorHandler : function(galleryFuncName, callback) {
		Gallery.registerCallback(galleryFuncName + "OnErrorHandler", callback);
		return callback;
	},
	
	invokeOnErrorHandlers : function(galleryFuncName) {
		arguments[0] = galleryFuncName + "OnErrorHandler";
		Gallery.invokeCallbacks.apply(this, arguments);
	},
	
	addOnBeforeActionHandler : function(galleryFuncName, callback) {
		Gallery.registerCallback(galleryFuncName + "OnBeforeHandler", callback);
		return callback;
	},
	
	invokeOnBeforeActionHandlers : function(galleryFuncName) {
		arguments[0] = galleryFuncName + "OnBeforeHandler";
		Gallery.invokeCallbacks.apply(this, arguments);
	},
	
	addOnAfterActionHandler : function(galleryFuncName, callback) {
		Gallery.registerCallback(galleryFuncName + "OnAfterHandler", callback);
		return callback;
	},
	
	invokeOnAfterActionHandlers : function(galleryFuncName) {
		arguments[0] = galleryFuncName + "OnAfterHandler";
		Gallery.invokeCallbacks.apply(this, arguments);
	},
				
	registerCallback : function(callbackName, callback) {
		if (callback == null) {
			return;
		}
		if (Gallery.galleryСallbacks[callbackName] == null) {
			Gallery.galleryСallbacks[callbackName] = new Array();
		}	
		var i = 0;
		while (Gallery.galleryСallbacks[callbackName][i] != null) {
			i++;
		}
		Gallery.galleryСallbacks[callbackName][i] = callback;
	},
	
	// replaces all existing callbacks with the given name, with new one (e.g. overwrites all existing handlers) 
	setCallback : function(callbackName, callback) {
		Gallery.galleryСallbacks[callbackName] = new Array();
		Gallery.galleryСallbacks[callbackName][0] = callback;
	},
	
	getCallbacks : function(callbackName) {
		return Gallery.galleryСallbacks[callbackName];
	},
	
	invokeCallbacks : function(callbackName) {
		if (Gallery.galleryСallbacks[callbackName] != null) {
			var args = new Array();
			for (var i = 1; i < arguments.length; i++) {
				args[i - 1] = arguments[i];
			}
			var i = 0;
			while (Gallery.galleryСallbacks[callbackName][i] != null) {
				Gallery.galleryСallbacks[callbackName][i].apply(this, args);
				i++;
			}	
		}
	},
	
	canSubmitForm : function(f_name) {
		return Gallery.pendingSubmitRequests.indexOf(f_name) == -1;
	},
	
	addPendingSubmitRequest : function(f_name) {
		Gallery.pendingSubmitRequests.push(f_name);
	},
	
	removePendingSubmitRequest : function(f_name) {
		var index = Gallery.pendingSubmitRequests.indexOf(f_name);
		if (index != -1) {
			Gallery.pendingSubmitRequests.splice(index, 1);
		}
	}
};