(function($){
	
	
	$.extend({
		adsCollector : new function() {
			/**
			 * PROPERTIES
			 */
			var position = {};
			var anchor = {};
			var counter = 0;
			var adService = document.WebRoot + '/remote/remoteAdService.cfc';
			
			/*
			 * Ask the server when all information is collected 
			 */
			$(function(){
				$.adsCollector.askServer();
			});
			
			
			/*
			 * Public functions
			 */
			return {
				
				/**
				 * Public functions
				 */
				insert : function(pos,className){
					var identifier = "AD_ANCHOR_" + Math.ceil(Math.random() * 100000);
					
					// store anchors
					anchor[identifier] = {
						"name": pos
						, "className" : className
					};
					
					// store anchor for each position
					if ( typeof (position[pos]) === 'undefined') {
						position[pos] =  [];	
					}
					
					position[pos].push(identifier);
					
					// write an anchor
					this.writeAnchor(identifier);
				},
				
				askServer : function(){
					var _self = this, positionlist = [];
					
					for (var key in anchor) {
						positionlist.push( anchor[key].name );
					}

					$.ajax({
						type: "post",
						url: adService + '?method=elements&returnformat=json',
						data: {
							placements: positionlist
						},
						success: function(e){
							for (var key in e){
								var s = e[key]
								, l = position[key]
								, wrap = jQuery("<div />")
									.addClass("ad-common")
								, ad;
							
								for (var i=0; s.length > i; i++) {
									ad = wrap.clone();
									// copy position name
									s[i].position = key;

									if (anchor[ l[i] ].className.length > 0 ) {
										ad.addClass(anchor[ l[i] ].className);
									}
									
									switch( s[i].type ){
										case 'html':
											ad = _self.iframe(ad, s[i]);
											break;
										case 'image':
											ad = _self.image(ad, s[i]);
											break;
										case 'flash':
											ad = _self.flash(ad, s[i]);
											break;
									}
									jQuery(document.getElementById( l[i] )).replaceWith(ad);
									
									//cleanup 
									delete anchor[ l[i] ];
								}
							}
							
							// remove the unused elements
							$.adsCollector.cleanup();
						},
						dataType: "json"
					});
				},
				
				writeAnchor : function(ident){
					document.write('<span id=\"' + ident + '\"></span>');
				},
				
				
				increment : function(){
					counter+1;
				},
				
				cleanup : function() {
					var keys = [], a = anchor;
					for (var key in a){
						$( document.getElementById(key) ).remove();
						delete anchor[ key ];
					}
					
				},
				image : function(wrap, e){
					wrap.addClass("ad-image");
					$('<a><img /></a>')
						.attr({ href : e.link })
						.click(function(){
							// register ad
							$.post(adService + '?method=registerStatistics&returnformat=plain',{
								adid : e.adid 
								, type : 2
							});
							// google analytics
							if (typeof pageTracker === 'object'){
								try {
									pageTracker._trackPageview('/adStats/' + e.adid + '/' + e.position );
								} catch (e){}
							}
						})
						.find('>img')
						.attr({ src : e.src })
						.end()
						.appendTo(wrap);
					return wrap;
				},
				
				flash : function(wrap,e){
					wrap.addClass("ad-flash");
					wrap.flash({
						src: e.src,
						flashvars: {
							hyperlink: e.link
							//, clickTAG: protocol + '//' + hostname + pathname + '?adid=' + a.adid + '&page=' + window.location.href
						}
					}, {
						version: 9
					}, function(htmlOptions){
						$this = $(this);
						htmlOptions.wmode = "transparent";
						$this.append($.fn.flash.transform(htmlOptions));
					});
					
					return wrap;
				},
				
				iframe : function(wrap,e){
					wrap.addClass("ad-iframe");
					$('<iframe src="'+e.src+'" frameBorder="0" scrolling="false" />')
						.css("border","none").appendTo(wrap);
					return wrap;
				}
			}
		}
	});

})(jQuery);
