/**
* @author colliers
*/
GY.ADS = {

	init: function()
	{
		GY.ADS.slideshow = 0;
		
		$(document).ready(function(){
			// Set the ACT URL to use..
			var hitsACTurl = '';
			$.get('/global_misc/gy_hits_ACTurl', function(data) {
				if( data ) hitsACTurl = data;
				else hitsACTurl = '/?ACT=74';
				$(window).data('hitsACTurl', data);
			} );
			// Hit clickthourgh tracking using hits module; fire off a tracking hit
			// Gets params from htype and entryid attributes
			$('.hitclkthru').click( function(e)
				{
					var link = $(this).attr('href');
					var target = $(this).attr('target');
					var eeHitsType = $(this).attr('htype');
					var entryID = $(this).attr('entryid');
					if( target != '_blank' ) e.preventDefault();
					$.ajax({
				    	url: hitsACTurl + '&t=' + eeHitsType + '&i=' + entryID,
					    success: function() {
								if( target != '_blank' ) document.location = link;
							},
					    error: function() {
								if( target != '_blank' ) document.location = link;
							}
				  });
				}
			);
			var pg_ids = "";
			var ad_ids = "";
			var sl_ids = "";
			$('.adspot[data-ox-aid]').each(function(index){
				ad_ids += $(this).attr("data-ox-aid")+",";
			});
			$('.adspot[data-ox-pid]').each(function(index){
				pg_ids += $(this).attr("data-ox-pid")+",";
			});
			$('.adspot[data-ox-sid]').each(function(index){
				sl_ids += $(this).attr("data-ox-sid")+",";
				GY.ADS.slideshow = 1;
			});
			// console.log("http://ox-d.fclmedia.com/w/1.0/arj?auid="+ad_ids+"&pgid="+pg_ids+sl_ids+"&callback=?&url="+window.location.href+"&cb="+Math.floor(Math.random()*100001));
			var openXurl = "http://ox-d.fclmedia.com/w/1.0/arj?auid="+ad_ids+"&pgid="+pg_ids+sl_ids+"&callback=?&url="+window.location.href+"&cb="+Math.floor(Math.random()*100001);
			//console.log(document.cookie);
			$.ajax( {
				url: openXurl,
				dataType: 'jsonp',
				success: function(data) {
					$.each(data.ads.ad,function(index){
						var _this = this;
						var ad_id = this.creative[0].media;					
						//alert(this.creative[0].tracking.impression);
						var impression_pixel = "<img src='"+this.creative[0].tracking.impression+"' width='0px' height='0px' class='hidden noborder'/>";
	//					var hitsImpressionPixel = hitsACTurl + '&t=' + eeHitsType + '&i=' + entryID
						var click_pixel = this.creative[0].tracking.click.replace("http://ox-d.fclmedia.com/", "/oxdfcl/");

						if(ad_id && impression_pixel && click_pixel)
						{
							if(sl_ids.indexOf(this.adunitgroup) >= 0 && isNaN(ad_id) && impression_pixel)
							{				 
								 $markup = $(_this.html);
								 $markup.attr("alt", " ");
								 $markup.attr("title", " ");
								 $markup.attr("entryid", this.adunitid);
								 $markup.attr("htype", '115');
								
								 //this add is stand alone so build it and append to the corresponding container
								 //alert(".adspot[data-ox-sid='"+_this.adunitgroup+"'] .slider");
								 $(".adspot[data-ox-sid='"+_this.adunitgroup+"'] .slider").append($markup.not('div'));
								 $(".adspot[data-ox-sid='"+_this.adunitgroup+"']").css("cursor:pointer");
								 $("body").append(impression_pixel);

								 GY.ADS.loadNivo = 1;
							}
							if(this.adunitgroup && !isNaN(ad_id))
							{
								var _this = this;
								// this ad is part of a group so build it and append to the corresponding container
								var product_data = "";								  
				
								GY.ADS.buildAdFromOpenx(ad_id,'108','77', this.adunitgroup, function(product_data)
								{
									if( '3170' == _this.adunitgroup && $('.istopoffers').length ) // top offers
										var $adcontent = $( product_data );
									else
										var $adcontent = $('<div class="grid g1-3">'+product_data+"</div>"+impression_pixel);
									$adcontent.find('a').click(
									function(e){
									  // IE fix for cross domain permissions - use proxypassed address
									  $('.loading-centre').remove();
									  $(this).append( '<span class="loading-centre"> </span>');
									  var link = $(this).attr('href');
									  var target = $(this).attr('target');
									  if( target != '_blank' ) e.preventDefault();
									  // Defer existing clickthrough trapping and link realisation
									  var clickNgo = function() {
										  $.ajax({
										    url: click_pixel,
										    success: function() {
										      if( target != '_blank' ) window.location = link;
										      else $('.loading-centre').remove();
										    },
										    error: function() {
										      if( target != '_blank' ) window.location = link;
										      else $('.loading-centre').remove();
										    }
										  });
									  }	
									  // Added by appleyap 9/10/11 - hits module clickthroughs
									  if( $(this).attr('htype') != 'undefined' )
									  {
										var newHtype = $(this).attr('htype') - -1; // Craftily convert to int and add 1
										  $.get(
											  hitsACTurl + '&t=' + newHtype + '&i=' + $(this).attr('entryid'),
											  clickNgo );
									  }
									  else clickNgo;
									  // End added by appleyap
									}
									);

									$(".adspot[data-ox-pid='"+_this.adunitgroup+"']").append($adcontent);
									//increment the counter
									var count = ($(".adspot[data-ox-pid='"+_this.adunitgroup+"']").find(".grid").length);
									var mod = parseInt(count) % 3;
									if( parseInt(mod) == 0 && parseInt(count) )
									{									
										$(".adspot[data-ox-pid='"+_this.adunitgroup+"']").append('<div class="clear">&nbsp;</div>');
									}
								});

							}
							else if(!isNaN(ad_id))
							{
								var _this = this;
								//this add is not part of a group so build it and append to the corresponding container
								var product_data = "";
								GY.ADS.buildAdFromOpenx(ad_id,'146','105',this.adunitid,function(product_data) {
									var $adcontent = $(product_data+impression_pixel);
									$adcontent.find('a').click(
										function(e) {
											$('.loading-centre').remove();
											$(this).append( '<span class="loading-centre"> </span>');
											var link = $(this).attr('href');
											var target = $(this).attr('target');
											var eeHitsType = $(this).attr('htype') - -1;
											var entryID = $(this).attr('entryid');
											if( target != '_blank' ) e.preventDefault();
											$.ajax({
										    	url: hitsACTurl + '&t=' + eeHitsType + '&i=' + entryID,
											    success: function() {
														if( target != '_blank' ) document.location = link;
														else $('.loading-centre').remove();
													},
											    error: function() {
														if( target != '_blank' ) document.location = link;
														else $('.loading-centre').remove();
													}
										  });
										}
									)
								  $(".adspot[data-ox-aid='"+_this.adunitid+"']").append($adcontent);
								});
							}
							else
							{
								var _this = this;
								if(ad_id.indexOf("src=") < 0)
								{
								  ad_id = _this.html+impression_pixel;
								}
								else
								{
								  ad_id+=impression_pixel;
								}
								//this add is stand alone so build it and append to the corresponding container
								$(".adspot[data-ox-aid='"+this.adunitid+"']").append(ad_id);
								$(".adspot[data-ox-aid='"+this.adunitid+"']").css("cursor:pointer");
							}
						}
					});
					if(GY.ADS.slideshow && GY.ADS.loadNivo)
					{					
						$.getScript(
							"/js/nivo-slider/jquery.nivo.slider.pack.js",
							function() {
								$('.slider').nivoSlider({
							      effect:'fade',
							      pauseTime:4500,
							      keyboardNav:false/*,
							      afterChange: function() {
							      	var thisEntry = $(this).find('a:visible:first');
							      	var eid = thisEntry.attr('entryid');
							      	if( (typeof eid) !== 'undefined' )
							      	{
							      		$.get( $(window).data('hitsACTurl')+'&t=114&i='+eid );
							      		thisEntry.removeAttr('entryid', 'tracked');
							      	}
							      }*/
								});
							}
						);
					}
				},
				error: function(data1, data2) {
					//console.log('error loading openX', data1, data2);					
				}
			});
		});
	},

	buildAdFromOpenx: function(id,width,height,meta,callback)
	{
		if( '3170' == meta ) // 6 x 'some ideas' block
		{
			var htype = 103;
			if( $('.istopoffers').length ) var theUrl = '/products/load_offers_via_openx/'+id;
		}
		else if( '10677' == meta ) // 'idea of the month'
		{
			var htype = 105;
		}
		else if( '23250' == meta ) // 'idea of the week'
		{
			var htype = 107;
		}
		if( !theUrl )
		{
			var theUrl = '/products/load_product_via_openx/'+id+'/'+width+'/'+height;
			if( htype ) theUrl += '/'+htype;
		}
		$.ajax({
			url: theUrl,
			dataType: 'html',
			async: true,
			success: function(product_data){	    
			  callback(product_data);
			}
		});
	}
};

