﻿/// <reference path="jquery-1.3.2.min.js"/>

OWL.styler = OWL.styler || {};

(function() {

	var that = OWL.styler;
	that.eventAffiliateID = -1;

	var thatObj = {
		rotateAdsWithInterval: function(interval, eaId, pinId) {
			//rotate immediately
			that.rotateAds(0, eaId, pinId);
			//set interval
			setInterval(
				function() { that.rotateAds(interval, eaId, pinId) }
				, interval
			);
		},
		rotateAds: function(interval, eaId, pinId) {

			//get ads
			$.ajax({
				type: "get",
				dataType: "json",
				url: '/Concert/GetAds/?eaId=' + eaId + '&pinId=' + pinId,
				cache: false,
				success: function(result) {
					that.setAds(interval, result);
				},
				error: function(xhr, textStatus, errorThrown) {
					////show error
					//OWL.helpers.defaultErrorCallback(xhr, textStatus, errorThrown);
				}
			});
		},
		setAds: function(totalInterval, adInfoList) {

			//[
			//	{"AdID":"2","ContainerID":"ad_bottom_1","AdUrl":"/Concert/BATestControl/2"}
			//	,{"AdID":"3","ContainerID":"ad_bottom_2","AdUrl":"/Concert/BATestControl/2"}
			//	,{"AdID":"4","ContainerID":"ad_bottom_3","AdUrl":"/Concert/BATestControl/2"}
			//]
			var length = adInfoList.length;
			if (length > 0) {

				var num = totalInterval / length;

				for (var i = 0; i < length; i++) {

					var interval = num * i;

					(function() {//set scope
						var iRescoped = i;

						setTimeout(
							function() {

								var adInfo = adInfoList[iRescoped];

								var container = $('#' + adInfo.ContainerID);
								//check if it's the same ad
								if (parseInt(container.attr('AdID')) !== adInfo.AdID) {
									container.attr('AdID', adInfo.AdID);

									//get html for each ad
									$.ajax({
										type: "get",
										dataType: "html",
										url: adInfo.AdUrl,
										success: function(result) {

											//insert ad
											container
												.empty()//clear contents
												.append(result)//set contents
												.animate({ opacity: 0.1 }, 000)//start opaque
												.animate({ opacity: 1.0 }, 750)//end at 1
											;
										},
										error: function(xhr, textStatus, errorThrown) {
											////show error
											//OWL.helpers.defaultErrorCallback(xhr, textStatus, errorThrown);
										}
									});
								}
							}
							, interval
						);
					})();
				}
			}
		},
		lastFunction: function() { }
	};

	OWL.lang.augmentObject(that, thatObj, true);
})();