var QAPI = {};
function trace(msg) {
	if (!QAPI.debug)
		return;
	if (console && console.log)
		console.log(msg);
}
QAPI.jsonpmode = true;
QAPI.apibaseurl = "http://ror.qooq.com/qooq_api/";
QAPI.debug = false;
QAPI.queue = [];
QAPI.inrequest = false;
QAPI.action = '';
QAPI.token = '';
QAPI.qas = '';
QAPI.cache_url = '';
QAPI.logged = false;
QAPI.after_init = {};
QAPI.qooqurl = ""; // pour le go qooq
QAPI.islocal = false;
QAPI.goqooq = "http://www.qooq.com";
QAPI.initTry = 0;
QAPI.apikey = '';
/*
 * Init de l'api
 */
QAPI.init = function(api_key, fct, debug, json) {
	if ((debug != undefined) && debug)
		QAPI.debug = true;
	if ((json != undefined) && json)
		QAPI.jsonpmode = false;
	QAPI.apibaseurl = QAPI.getPathToSelf();
	QAPI.after_init = fct;
	if (QAPI.qas != ''){
	    // api deja initialisee
	    QAPI.after_init(success, json);
	    QAPI.after_init = 0;
	    return;
	}
	QAPI.apikey = api_key;
	QAPI.sendRequest('init', {
		'api_key' : api_key
	}, QAPI._iniCallBack);
};
QAPI._iniCallBack = function(success, json) {
	if (success) {
		QAPI.token = json.token;
		QAPI.qas = json.qas;
		QAPI.cache_url = json.cache_url;
		if (QAPI.qooqurl == "") {
			QAPI.qooqurl = json.qooqurl+"qooq/";
		}
	}
	else{
	    if (!QAPI.jsonpmode && QAPI.initTry == 0){
		QAPI.jsonpmode = true;
		QAPI.initTry = 1;
		// on retry en jsonp
		QAPI.sendRequest('init', {
			'api_key' : QAPI.apikey
			    }, QAPI._iniCallBack);

		return;
	    }

	}
	QAPI.logged = false;
	QAPI.after_init(success, json);
	QAPI.after_init = 0;
}
/*
 * loggin
 */
QAPI.fblogin = function(fb_id, fct) {
	QAPI.after_login = fct;
	QAPI.sendRequest('fblogin', {
		'fb_id' : fb_id
	}, QAPI._loginCallBack);
};
QAPI.login = function(email, pass, fct) {
	QAPI.after_login = fct;
	QAPI.sendRequest('fblogin', {
		'email' : email,
		'pass' : pass
	}, QAPI._loginCallBack);
};
QAPI.login_main = function(email, pass, fct) {
	QAPI.after_login = fct;
	QAPI.sendRequest('login', {
		'email' : email,
		'pass' : pass
	}, QAPI._loginCallBack);
};
QAPI._loginCallBack = function(success, json) {
	if (success) {
		QAPI.logged = true;
		QAPI.goqooq = json.goqooq;
	}
	QAPI.after_login(success, json);
	QAPI.after_login = 0;
}
/*
 * creation de compte
 */
QAPI.create = function(email, pass, firstname, lastname, civility, extra, fct) {
	objsend = {
		'email' : email,
		'pass' : pass,
		'firstname' : firstname,
		'lastname' : lastname,
		'civility' : civility,
		'extra' : extra
	};
	QAPI.sendRequest('create', objsend, fct);
};
QAPI.lostpassword = function(email,fct) {
	param = {};
	param["email"] = email;
	QAPI.sendRequest('lost_password_by_mail', param, fct);
};
QAPI.qooqinfo = function(fct) {
	QAPI.sendRequest('qooqinfo', {}, fct);
};
QAPI.query = function(query, fct, qooq_client_id) {
	param = {};
	param["query"] = query;
	if (qooq_client_id != undefined)
		param["qooq_client_id"] = qooq_client_id;
	QAPI.sendRequest('query', param, fct);
};
QAPI.mappedfbids = function(idarray, fct) {
	QAPI.sendRequest('mappedfbids', {
		"fb_ids" : idarray.join(',')
	}, fct);
};
QAPI.fbuserinfo = function(fct) {
	QAPI.sendRequest('fbuserinfo', {}, fct);
};
QAPI.fbmap = function(fb_id, force, fct) {
	QAPI.sendRequest('fbmap', {
		'fb_id' : fb_id,
		'force' : force
	}, fct);
}
QAPI.fbunmap = function(fct) {
	QAPI.sendRequest('fbunmap', {}, fct);
}
/* popup confidentialité Facebook */
QAPI.fb_popupaccepted = function(fct) {
	QAPI.sendRequest('popupaccepted', {}, fct);
}
/* partage de recettes perso sur facebook */
QAPI.fb_share = function(qooq_id, idAr, fct) {
	QAPI.sendRequest('fb_share', {
		ids: idAr.join(','),
		qooq_client_id: qooq_id
	}, fct);
};
QAPI.fb_share_all = function(qooq_id, fct) {
	QAPI.sendRequest('fb_share', {
		all: true,
		qooq_client_id: qooq_id
	}, fct);
};
/* dé-partage de recettes perso sur facebook */
QAPI.fb_unshare = function(qooq_id, idAr, fct) {
	QAPI.sendRequest('fb_unshare', {
		ids: idAr.join(','),
		qooq_client_id: qooq_id
	}, fct);
};
QAPI.fb_unshare_all = function(qooq_id, fct) {
	QAPI.sendRequest('fb_unshare', {
		all: true,
		qooq_client_id: qooq_id
	}, fct);
};
/* récupération de recettes d'ami sur facebook */
QAPI.fb_get = function(qooq_id, idAr, fct) {
	QAPI.sendRequest('fb_get', {
		ids: idAr.join(','),
		qooq_client_id: qooq_id
	}, fct);
};
QAPI.fb_get_all = function(qooq_id,  fct) {
	QAPI.sendRequest('fb_get', {
		all: true,
		qooq_client_id: qooq_id
	}, fct);
};
/* suppression de recettes d'ami sur facebook */
QAPI.fb_unget = function(qooq_id, idAr, fct) {
	QAPI.sendRequest('fb_unget', {
		ids: idAr.join(','),
		qooq_client_id: qooq_id
	}, fct);
};
QAPI.fb_unget_all = function(qooq_id,  fct) {
	QAPI.sendRequest('fb_unget', {
		all: true,
		qooq_client_id: qooq_id
	}, fct);
};
/* partage ou pas de favorites, profil culinaire ou planning sur Facebook */
QAPI.fb_settings= function(facebook_id, qooq_id, typeStr, sharedBool, fct) {
	QAPI.sendRequest('fbsettings', {
		fbId: facebook_id,
		qooq_client_id: qooq_id,
		query: typeStr,
		shared: sharedBool
	}, fct);
};
/*
 * ENVOI DE REQUETE
 */
QAPI.sendRequest = function(actionid, data, callback) {
    if (QAPI.jsonpmode){
	url = QAPI.apibaseurl + actionid + ".jsonp";
    }
    else{
	url = QAPI.apibaseurl + actionid + ".json";
    }
	req = {
		"url" : url,
		"data" : data,
		"callbackid" : actionid,
		"callback" : callback
	};
	QAPI.queue.push(req);
	QAPI._processQueue();
};
QAPI._processQueue = function() {
	if (QAPI.inrequest)
		return;
	if (QAPI.queue.length) {
		req = QAPI.queue.shift();
		QAPI._processRequest(req.url, req.data, req.callbackid, req.callback);
	}
}
QAPI._processRequest = function(url, data, callbackid, callback) {
	QAPI.inrequest = true;
	QAPI.testReponse = callback;
	if (QAPI.token) {
		data.authenticity_token = QAPI.token;
	}
	if (QAPI.qas) {
		data.qas = QAPI.qas;
	}
	data.ts = new Date().getTime();
	var paramObj = {
		noCache : true,
		url : url,
		data : data,
		onFailure : function(xhr) {
			trace('onFailure : code erreur : ' + (xhr ? xhr.status : null));
			QAPI.testReponse(false, 'onFailure : code erreur : '
			+ (xhr ? xhr.status : null));
			QAPI.inrequest = false;
			QAPI._processQueue();
		},
		onSuccess : function(repJSON, repText) {
			if (repJSON.errors.status) {
				if (QAPI.testReponse) {
					QAPI.testReponse(false, repJSON);
				}
			} else {
				if (QAPI.testReponse) {
					QAPI.testReponse(true, repJSON);
					QAPI.myAjax = {};
				}
			}
			QAPI.inrequest = false;
			QAPI._processQueue();
		}
	}
	paramObj.callBackIndex = callbackid;
	if (QAPI.jsonpmode)
	    QAPI.myAjax = new Request.JSONP(paramObj).send();
	else
	    QAPI.myAjax = new Request.JSON(paramObj).send();
};
/*
 * fonction synchrone qui renvoie une url pour aller a qooq
 */
QAPI.goqooqurl = function(section, item, qooqspecialurl) {
	if (section == undefined)
		section = '';
	if (item == undefined)
		item = '';
	if (qooqspecialurl != undefined)
		url = qooqspecialurl
	else {
		if (QAPI.islocal)
			url = "/qooq/gofromapi/";
		else
			url = QAPI.qooqurl+'gofromapi/';
	}
	url += "?section=" + section;
	url += "&item=" + item;
	url += "&qas=" + QAPI.qas;
	return url;
}

// QAPI.
QAPI.getHostname = function (str) {
	var re = new RegExp('\://([^/]+)', 'im');
	return str.match(re)[1].toString();
};
QAPI.getDocumentRootPath = function() {
	return document.location.protocol+'//'+document.location.hostname;
};
QAPI.getPathToSelf = function() {
	var myName = /(^|[\/\\])qooq_api\.js(\?|$)/;
	var myReplacer = /qooq_api\.js.*/;
	var scripts = document.getElementsByTagName("script");
	for ( var i = 0; i < scripts.length; i++) {
		var src;
		if (src = scripts[i].getAttribute("src")) {
			if (src.match(myName)) {
				src = src.replace(myReplacer, '');
				if (src.match(/^http/)) {
					QAPI.islocal = false;
					// go qooq url
					if (src.match("ajaxcall")) {
						var apiBaseReplacer = /ajaxcall.*/;
						qooqurll = src;
						qooqurll = qooqurll.replace(apiBaseReplacer,'');
						qooqurll = qooqurll + "qooq/";
						QAPI.qooqurl = qooqurll;
					}
					return src;
				} else {
					QAPI.islocal = true;
					return QAPI.getDocumentRootPath() + src;
				}
			}
		}
	}
}

