/**
* Формирование кросс-доменного запроса(jsonp)
*/
/**
 -------------------------------------------------------------------
 File    : emuc.js
 Description : Формирование кросс-доменного запроса(jsonp)
 Created : 06 Dec 2011 by Alexandr Vorkov <AlexandrVorkov@gmail.com> 
 @version $Revision$
 -------------------------------------------------------------------
  */
 /**
 @author IQOM <iqom@isqom.org> [http:isqom.org]
 @copyright 2008 IQOM R&D Group. 

 The contents of this file are subject to the GNU GPL license,
 Version 3, (the "License"); you may not use this file except in
 compliance with the License. You should have received a copy of the
 GNU GPL license along with this software. If not, it can be
 retrieved via the world wide web at http:www.gnu.org/copyleft/gpl.html.

 Software distributed under the License is distributed on an "AS IS"
 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 the License for the specific language governing rights and limitations
 under the License.

 The Initial Developer of the Original Code is IQOM R&D Group.
 All Rights Reserved.
 */
/**
* Delegates 
* @type Object 
*/
var EMUCJsonpRequest = {};
/**
* url {String} - url запроса
* params {Object} - параметры запроса. Пример: {p1:'a',p2:'b'}
* disableCaching {Boolean} - кешировать или нет(добавляется ли уникальный параметр t или нет). По умолчанию true.
* callback {Function} - Ф-я которая обрабатывает ответ.
* r {Boolean} - если равно true, то callback добавится не как параметр, а как часть пути. 
* Название функции дописывается вместо /{myCallback}/. Пример:http://exemple.com/{myCallback}/ заменится на http://exemple.com/_F1564/.
* Пример: rJsonpRequest({url:'http://exemple.com',params:{a:'b',c:'v'},callback:function(){alert('a')}})
* EMUCJsonpRequest.rJsonpRequest({url:'http://exemple.com/{callback}/ds',params:{a:'b',c:'v'},callback:function(){alert('a')}})
*/
EMUCJsonpRequest.send = function(c) {
    //проверяем параметры
    if (!c.url || '' == c.url || ('function' != typeof (c.callback))) {
        return;
    }
    var callback = c.callback;
    var url = c.url;
    var disableCaching = c.disableCaching !== false ? true : false;
    var r = c.r !== false ? true : false;
    var params = typeof (c.params) == "object" ? c.params : {};
    /**
    * формируем хеш
    */
    function stringHash(pS) {
        var tH = 0; var tL = pS.length; for (var i = 0; i < tL; ++i) { tH = ((33 * tH) % 4294967296) + pS.charCodeAt(i); }
        return tH;
    }
    /**
    * формируем параметры	
    */
    function formParam(par) {
        var urlPar = '';
        for (var prop in par) {
            if ('' != urlPar) urlPar += '&';
            urlPar += prop + '=' + encodeURI(par[prop]);
        }
        return urlPar;
    }
    if (disableCaching) {
        params.t = new Date().getTime();
    }
    //сохраняем делегата
    var p = "_F" + stringHash(url + ((url.indexOf('?') != -1) ? '&' : '?') + encodeURI(formParam(params)));
    if (disableCaching) {
        //если мы уже использовали этот параметр(для отмены кеширования), 
        //то не нужно его передавать еще как параметр
        delete params.t;
    }
    EMUCJsonpRequest[p] = callback;
    if (r && (url.indexOf('/{callback}/') != -1)) {
        url = url.replace(/\/\{callback\}\//, '/EMUCJsonpRequest.' + p + '/');
    } else {
        params.callback = "EMUCJsonpRequest." + p;
    }
    //Делаем get запрос
    var EMUCscript = document.createElement('script');
    EMUCscript.type = 'text/javascript';
	EMUCscript.async = true;
    EMUCscript.src = url + ((url.indexOf('?') != -1) ? '&' : '?') + formParam(params);
    document.body.appendChild(EMUCscript);
};

