
/**
 * The "bind()" function extension from Prototype.js, extracted for general use
 * 
 * @author Richard Harrison, http://www.pluggable.co.uk
 * @author Sam Stephenson (Modified from Prototype Javascript framework)
 * @license MIT-style license
 * @see http://www.prototypejs.org/
 */
Function.prototype.bind = function(){
    // http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions:arguments
    var _$A = function(a){return Array.prototype.slice.call(a);}

    if(arguments.length < 2 && (typeof arguments[0] == undefined)) return this;

    var __method = this, args = _$A(arguments), object = args.shift();

    return function() {
      return __method.apply(object, args.concat(_$A(arguments)));
    }
}

Array.prototype.remove=function(s){
    var index = this.indexOf(s);
    if(index != -1) {
        this.splice(index, 1);
    }                        
}

Function.prototype.remove = function() {
}

if (typeof [].indexOf == 'undefined') {
	Array.prototype.indexOf = function(v, n){
		n = (n == null) ? 0 : n; var m = this.length;
		
		for(var i = n; i < m; i++) {
			if(this[i] == v) return i;
		}
		
		return -1;
	};
}


var Application = Class.create({
	
	COOKIE_SESSION_NAME:  'userId',
    
    REQUEST_STATUS_OK    : 'ok',
    REQUEST_STATUS_ERROR : 'error',
    REQUEST_STATUS_INFO  : 'info',
    MAIN_BODY_CONTAINER  : 'main-content',
    
	ajaxRequest: function(url, options) {
		
		this._callAjax('GET', url, {}, options);
	},

	ajaxPost: function (url, postFields, options) {
        
		postFields = jQuery.extend(false, postFields, { 
			sessionId: $.cookie(this.COOKIE_SESSION_NAME) == null ? '' : $.cookie(this.COOKIE_SESSION_NAME).substring(0, 32)
		});
		this._callAjax('POST', url, postFields, options);
		return false;
	},

	ajaxPostWithReload: function (url, postFields, options) {
        
		if (typeof postFields == 'undefined')
			postFields = {}
		if (typeof options == 'undefined')
			options = {}
		options.onSuccess = function (resp) {
			window.location.reload();
		};
		this.ajaxPost(url, url, options);
		return false;
	},
	
	ajaxForm: function (id, options) {

		if (typeof options.onSuccess != 'function') {
			options.onSuccess = this.processDefaultAjaxFormResponse.bind(this, id);
		}

		$('#' + id).ajaxForm({
			data: { 
				sessionId: $.cookie(this.COOKIE_SESSION_NAME) == null ? '' : $.cookie(this.COOKIE_SESSION_NAME).substring(0, 32)
			},
			dataType:  'json',
			beforeSubmit: options.beforeSubmit,
			complete:  this._parseAjaxResponse.bind(this, options)
		}); 
	},
	
	
	_callAjax: function (method, url, postData, options) {

		$.ajax({
			type: method,
			url: url,
			data: postData,
			dataType: 'json',
			complete: this._parseAjaxResponse.bind(this, options)
		});
	},
	
	_parseAjaxResponse: function (options, obj, textStatus, set) {

		this._parseAjaxResponse.handleCallback = function (callback, status, responseData) {

			if (typeof callback == 'function') {
				callback(responseData, status);
				return true;
			} else if (typeof callback == 'string') {
				this.showMsg(callback);
				return true;
			}
			return false;
		}.bind(this);

		var status = obj.status;
		try {
			var responseData = $.evalJSON(obj.responseText);
		} catch (err) {
			// if we cant deserialize json output
			status = 500;
			var responseData = {};
		}

		// on success
		if (status == 200) {
			if (typeof options['onSuccess'] == 'function') {
				var func = options['onSuccess'];
				func(responseData);
			}
			return true;
		}

		// on error
		if (typeof options['errorList'] == 'undefined' || 
				!this._parseAjaxResponse.handleCallback(options['errorList'][status], status, responseData) && 
				!this._parseAjaxResponse.handleCallback(options['errorList']['default'], status, responseData)) {
			this.processAjaxError(obj);
		}
	},
	
	
	processAjaxError: function (obj) {

		switch (obj.status) {
			case 0:
				break;
			case 403:
				return;// (Application_lang.ajax_forbidden, this.REQUEST_STATUS_ERROR);
			case 404:
				return;// (Application_lang.ajax_notFound, this.REQUEST_STATUS_ERROR);
            case 409:
                if (obj.responseText.length > 0) 
                    return; //(obj.responseText, this.REQUEST_STATUS_ERROR);
                else
                   return; //(Application_lang.ajax_internalServerError, this.REQUEST_STATUS_ERROR); 
			case 500:
			default:
				return; //(Application_lang.ajax_internalServerError, this.REQUEST_STATUS_ERROR);
		}
	},
	
	
	processDefaultAjaxFormResponse: function (id, obj) {
		
		var errorMsgId = id + 'ErrorMsg';
		if (!obj.success) {
			document.getElementById(errorMsgId).innerHTML = obj.error;
		} else {
			window.location.reload();
		}
		return false;
	}
});

var application = new Application();

Application.historyCallbacks = {};
Application.registerHistoryCallback = function(prefix, callback) {
	Application.historyCallbacks[prefix] = callback;
	/* check if new callback wants to handle current hash */
	var currentPrefix = location.hash.replace(/^#/, '').split('/')[0];
	if (prefix == currentPrefix)
		Application._historyCallback(location.hash.replace(/^#/, ''));
}
Application.getHashValue = function(prefix, params) {
	return prefix + '/' + params.join('/');
}
Application._historyCallback = function(hashValue) {
	hashValue = hashValue.split('/');
	var prefix = hashValue[0];
	if (Application.historyCallbacks[prefix] == undefined) {
		return;
	}
	hashValue.splice(0, 1);
	Application.historyCallbacks[prefix](hashValue);
}
