(function($) {

    var references = {}, adSuffix = '_ajax_holder_';
    var count = 0
    var refresh = function() { 
        var i = references.slotIds.length, container;
        while(i --) {
            try {
                container = $('#' + references.slotIds[i])[0];
                container.appendChild(references.adSenseElementRefs[i]);
                count++;
//                references.ads[i].refresh(references.options[i]);
            } catch (e){
            }

        }
    }

    var saveElementReferences = function(){
        if(references.adSenseElementRef && references.adSenseElementRef.length) {
            var i = references.adSenseElementRef.length, element;
            while(i --) {
                element = references.adSenseElementRef[i];
                element.parentNode.removeChild(element);
            }
        }
    }
    objectCopy = function(obj){
        var a = {}
        for (key in obj){
            a[key] = obj[key]
        }
        return a;
    }
    $.adSenseAjax = {
        /**
         * Initialize ajax adSense. We assume that first call is made on document ready and 
         * elements with slotIds are in DOM
         * @param {String} clientIdentifier - adSenseAcount indentifier
         * @param {Array} slotsIds - element ids where adSense should be placed
         * @param {Object} options - object with adSense options
         * 
         */
        init: function(slotIds, options){
            references.slotIds = slotIds;
            references.adSenseElementRefs = [];
            references.ads = [];
            references.options = []
            var i = slotIds.length, element, adSenseId;
            while (i--) {
                try {
                   //exception will be thrown if slot does not exist 
                    opts = objectCopy(options);
                    adSenseId = slotIds[i] + adSuffix + i;
                    opts['container'] = adSenseId // slotIds[i];
                    //create element where ad will be placed
                    element = document.createElement('div');

                    element.id = adSenseId;
                    references.options[i] = opts;
                    $('#' + slotIds[i])[0].appendChild(element);
                    references.adSenseElementRefs[i] = element;//save element reference
                    references.ads[i] = new google.ads.search.Ad(opts);//save ad reference
                } catch (e) {
                    // do nothing
                }
            }
        },
        /**
         * @returns {Object} callbacks, object contains after and before properties as search widget API defines
         * @see {searcher.addcallbacks}
         */
        getCallbacks: function(){
            return { 
                after:  refresh,
                before: saveElementReferences
            };
        }
    }

})(jQuery)
