/**********************************************************************************
 * Set  of  classes and functions that will help generate AJAX queries using jQuery
 * library and parse responses.
 * 
 * The MIT License
 * 
 * Copyright (c) 2008 Victor Denisenkov aka Mr.V!T
 * 
 * Permission  is hereby granted, free of charge, to any person obtaining a copy of
 * this  software  and  associated documentation files (the "Software"), to deal in
 * the  Software  without  restriction,  including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the  Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 * 
 * The  above  copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR  A  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT  HOLDERS  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN  AN  ACTION  OF  CONTRACT,  TORT  OR  OTHERWISE,  ARISING  FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @package vit-lib
 * @author Victor Denisenkov aka Mr.V!T
 * @version 1.0
\**********************************************************************************/

var ajaxReturn = function (status_place, destination) {
	if (status_place) this.statusPlace = status_place;
	if (destination) this.controller = destination;
} //CONSTRUCTOR ajaxReturn

ajaxReturn.prototype = {
	controller	: '',
	post		: {},
	ModalDialog	: '',
	ModalLoader	: '',
	statusPlace	: '',
	
	onSuccess	: function (data) {},
	onError		: function (data) {},
	onFail		: function (data) {},
	onSimple	: function (data) {},
	onStart		: function () {},
	onStatus	: function (html) {
	}, //FUNC onStatus

	parseResult	: function (result) {

		var res		= {};
		res._post	= this.post;

		var data		= result.split('-- --=- CUT -=-- --');
		res._message	= data[0];
		if ( !res._message ) res._message = '&nbsp;';
		
		res._fullhead	= data.length != 1;
		
		if (res._fullhead) {
			var head		= JSON.parse(data[1]);
			res._major	= head.major;
			res._minor	= head.minor;
			res._status	= head.minor;
			res._fields	= head.fields;
//			res.data	= [];
			var di = 2;
			if ( res._fields.length != 0 ) {
				for (i = 0; i < res._fields.length; i++) {
					res[res._fields[i]] = data[di];
					di++;
				} //FOR each field
			} //IF was fields posted
		} //IF was full result
		return res;
	},//FUNC parseResult

	/*--------------------------------------------------------------------------------*\
	|	DoStatus
	|----------------------------------------------------------------------------------
	| Updates status.
	| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	|	Params:
	|		message		string		- Status message to display.
	|		callback	funciton	- Funciton to call.
	|		data		MIXED		- Data to pass to callback function.
	|	Return:
	|				bool		- ALways FALSE.
	\*--------------------------------------------------------------= by Mr.V!T =-----*/
	DoStatus	: function (message, callback, data) {
		
		if ( this.statusPlace && message ) jQuery('#'+this.statusPlace).html( status_string(message) );
		
		if ( callback instanceof Function ) callback(data);
		
		this.doModals('finish');
		
		return false;
	}, //FUNC DoStatus

	ajax_success	:  function (res) {
		var data = this.parseResult(res);
		
		if (this.statusPlace) jQuery('#'+this.statusPlace).html(data._message);
		
		var cb = this.onSimple;
		if ( data._fullhead ) 
			cb = ( data._major )? this.onSuccess : this.onError;
		
		this.DoStatus('', cb, data);
		
	}, //FUNC sucess

	ajax_error	: function (res) {
		
		this.DoStatus(data._message, this.onFail, res);
		
	}, //FUNC error

	postForm	: function (form_id, safe) {
		var _ar = this;
		
		if (!_ar.controller) return this.DoStatus('Invalid destination. Aborting.');
		
		if ( !form_id ) return this.postData();
		
		var form = (form_id.elements)? form_id : document.getElementById(form_id);
//		var form = (form_id instanceof HTMLFormElement)? form_id : document.getElementById(form_id);
//		var form = (form_id instanceof HTMLFormElement)? form_id : jQuery('#'+form_id).get();
		if ( !form ) return this.DoStatus('Can\'t find data to POST. Aborting.');
		
		if ( safe ) return this.postData( FormToObj(form) );
		
		if (_ar.statusPlace) insert_bar(_ar.statusPlace);
		
		this.doModals('start');
		
		this.onStart();

		var old_action = form.action;
		
		jQuery.ajaxUpload ({
			type		: 'POST', dataType : 'html',
			url		: _ar.controller,
			secureuri	: false,
			uploadform	: form,
			success		: function (res) {
				_ar.ajax_success(res);
			}, //FUNC success
			error		: function (res,status) {
				_ar.ajax_error(status);
			} //FUNC error
		}); //AJAX
		
		form.action = old_action;
		form.target = '';
		
		return false;
	}, //FUNC postForm

	postData	: function (post_data) {
		
		if ( !post_data ) post_data = {};
		
		this.post = post_data;
		var _ar = this;

		if (_ar.statusPlace) insert_bar(_ar.statusPlace);
		
		this.doModals('start');
		
		if (!_ar.controller) return this.DoStatus('Invalid destination. Aborting.');

		this.onStart();

		jQuery.ajax({
			type	: 'POST', dataType: 'html',
			url	: _ar.controller,
			data	: post_data,
			success		: function (res) {
				_ar.ajax_success(res);
			}, //FUNC success
			error		: function (res,status) {
				_ar.ajax_error(status);
			} //FUNC error
		}); //AJAX
		
		return false;
	}, //FUNC postData

	/*--------------------------------------------------------------------------------*\
	|	setModals
	|----------------------------------------------------------------------------------
	| Set modal windows parameters.
	| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	|	Params:
	|		dialog	string	- ID of window to use as Dialog.
	|		loader	string	- ID of window to use as loader window.
	|	Return:
	|			SELF
	\*--------------------------------------------------------------= by Mr.V!T =-----*/
	setModals	: function (dialog, loader) {
		
		this.ModalDialog = dialog;
		
		if ( !loader ) return this;
		
		tmp = document.getElementById(loader);
		if ( !tmp ) return this;
		
		this.ModalLoader = loader;
		
		return this;
	}, //FUNC setModals

	/*--------------------------------------------------------------------------------*\
	|	doModals
	|----------------------------------------------------------------------------------
	| Displays or hides modals windows.
	| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	|	Params:
	|		mode	string	- Status mode:
	|				  'start' - Set starting mode.
	|				  *other* - Finished mode.
	|	Return:
	|		NULL
	\*--------------------------------------------------------------= by Mr.V!T =-----*/
	doModals	: function ( mode ) {
		
		if ( mode == 'start' ) {
			if ( this.ModalLoader ) { 
				jQuery('#'+this.ModalDialog).jqm();
				jQuery('#'+this.ModalDialog).jqmHide();
				jqmShowCentered('#'+this.ModalLoader);
			} //IF loader is set
			
			if ( this.ModalDialog && !this.ModalLoader ) jqmShowCentered('#'+this.ModalDialog);
		} else { //IF
			if ( this.ModalLoader ) jQuery('#'+this.ModalLoader).jqmHide();
			if ( this.ModalDialog ) jqmShowCentered('#'+this.ModalDialog);
		} //IF
		
	} //FUNC doModals

} //CLASS ajaxReturn
