var full_base_path = 'http://www.sonypictures.com/RotatingAds/';

/*
Array.prototype.clone2 = function () {
	var a = new Array(); 
	for (var property in this) {
		a[property] = typeof (this[property]) == 'object' ? this[property].clone2() : this[property];
	} 
	return a
}
*/

function RotatingAds(){

	var xmlDoc = null;
	var x = null;
	var xml_array = new Array();
	var session_ads_index_array = new Array();
	var session_available_ads = new Array();
	var available_ads = new Array();
	var next_ad_count = 0;
	var ads_name = '';
	var ads_count = 0;
	var duplicates_eminent = false;
	var ads_per_page = 0;
	var img_path = '';
	var manipclass = '';
	
	function importXML(file, path, adsperpage, div_class)
	{
		img_path = full_base_path + path;
		ads_per_page = adsperpage;
		manipclass = div_class;

		if(navigator.appVersion.indexOf ( "Safari" ) != -1){
			var ajaxRequest;  // The variable that makes Ajax possible!
			var str;

			// Opera 8.0+, Firefox, Safari
			ajaxRequest = new XMLHttpRequest();

			// Create a function that will receive data sent from the server
			ajaxRequest.onreadystatechange = function(){
				if(ajaxRequest.readyState == 4){
					xmlDoc = ajaxRequest.responseXML;
					setXMLAttributes();
					populateAdDivs(div_class);
					close();
				}
			}

			ajaxRequest.open("GET", file, true);
			ajaxRequest.send(null);
		}else{

			if (document.implementation && document.implementation.createDocument)
			{
				xmlDoc = document.implementation.createDocument("", "", null);
				xmlDoc.onload = function(){
					setXMLAttributes();
					populateAdDivs(div_class);
					close();
				}
			}
			else if (window.ActiveXObject)
			{
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.onreadystatechange = function () {
					if (xmlDoc.readyState == 4) {
						setXMLAttributes();
						populateAdDivs(div_class);
						close();
					}
				};
			}
			else
			{
				alert('Your browser can\'t handle this script');
				return;
			}
			try
			{
				xmlDoc.load(file);
			}
			catch (e)
			{
				alert('broken');
			}


	    }
	}

	this.importXML = importXML;

	function populateAdDivs(div_class){
		var ad_divs = document.getElementsByTagName('div');
		//find all divs with class name
		for(var i=0; i<ad_divs.length; i++){
			if(ad_divs[i].className != null && ad_divs[i].className.indexOf(div_class) != -1){
				getNextAd(ad_divs[i]);//get next ad for this div
			}
		}
	}

	this.populateAdDivs = populateAdDivs;

	function getNextAd(obj){
		var rotation_index = session_ads_index_array.length;
		var ad_index = 0;
		var last_index_from_cookie = 0;
		var last_index_from_session = session_ads_index_array[rotation_index-1];

		last_index_from_cookie = getLastIndex(ads_name, ads_count);

		if(rotation_index > 0){//check if this is the first ad of this session
			ad_index = parseInt(getAvailableAd(last_index_from_session));//grab ad index from session
		}else if(last_index_from_cookie != null){//if this is first ad of the session, check if there is a cookie set
			ad_index = parseInt(getAvailableAd(parseInt(last_index_from_cookie)));//grab ad index from cookie
		}

		createImg(ad_index, obj);//create the image and populate the div

		session_ads_index_array[next_ad_count++] = ad_index;//increment ad count for this session
		session_available_ads[ad_index] = false;//set this ad unavailable for this session
	}

	this.getNextAd = getNextAd;

	function getAvailableAd(starting_index){
		var random_ad = false;
		var avail_ad = -1;
		var avail_ad2 = -1;
		var nexti = 0;
		starting_index = parseInt(starting_index);

		if(!random_ad){
			if(starting_index >= (ads_count-1)){
				starting_index = -1;
				//session_available_ads = available_ads.clone2();//repopulate ads into session when last index
				setXMLAttributes();//work around for resetting array instead of using cloning because cloning breaks wysiwyg editor for boards
			}
			nexti = starting_index+1;
			for(; nexti<ads_count; nexti++){//get next available ad starting from starting_index
				if(session_available_ads[nexti] !== false){
					return nexti;
					break;
				}
			}
			//if there are not enough ads to fill the ad spots, the spot will be populated with an available unexpired ad
			//session_available_ads = available_ads.clone2();//repopulate ads into session when no ads can be found
			setXMLAttributes();//work around for resetting array instead of using cloning because cloning breaks wysiwyg editor for boards
			if(ads_count < ads_per_page){
				return 0;
			}
			return parseInt(getAvailableAd(starting_index));

		}else{
			//random not implemented
		}
	}

	this.getAvailableAd = getAvailableAd;

	function setXMLAttributes(){
		var ads = xmlDoc.getElementsByTagName('ads');
		x = xmlDoc.getElementsByTagName('ad');
		ads_name = ads[0].getAttribute('cookiename');

		var today = new Date()
		var year = today.getYear()

		if(year<1000) 
			year+=1900
			 
		var today_date = (year * 10000) + ((today.getMonth()+1)*100) + (today.getDate());//get todays date as yyyymmdd

		for(var i=0; i<x.length; i++){
			var date = x[i].getElementsByTagName('date');
			var link = x[i].getElementsByTagName('link');
			if(((date[0].getAttribute('start') != null) && (date[0].getAttribute('start') != '') && (date[0].getAttribute('start') > today_date)) || ((date[0].getAttribute('expire') != null) && (date[0].getAttribute('expire') != '') && (date[0].getAttribute('expire') <= today_date))){	
			}else{//if start date set or expiration date set check if they have been triggered else
				available_ads[ads_count] = i;//add ad to the reference array
				session_available_ads[ads_count++] = i;//add ad to the session reference array
			}
		}

//		debug(session_available_ads,'');

		//set unavailable ads from previous session
		for(var i=0; i<ads_per_page; i++){
			if(parseInt(readCookie(ads_name+'['+i+']')) > -1){
				session_available_ads[parseInt(readCookie(ads_name+'['+i+']'))] = false;
			}
		}
	}

	this.setXMLAttributes = setXMLAttributes;

	function createImg(i, obj)
	{
		var ad_index = session_available_ads[i];
//		debug(session_available_ads, i + '-' + ad_index);
		var date = x[ad_index].getElementsByTagName('date');
		var img = x[ad_index].getElementsByTagName('img');
		var link = x[ad_index].getElementsByTagName('link');
		var html_anchor = document.createElement('A');

		//create anchor and img
		html_anchor.setAttribute('href',link[0].getAttribute('href'));
		var html_img = document.createElement('IMG')
		html_img.setAttribute('src',img_path + img[0].getAttribute('src'));
		html_img.setAttribute('alt',img[0].getAttribute('alt'));
		html_anchor.appendChild(html_img);
		html_anchor.setAttribute('target','_blank');
		html_anchor.setAttribute('title',img[0].getAttribute('alt'));
		obj.appendChild(html_anchor);//append to div
	}

	this.createImg = createImg;

	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	this.createCookie = createCookie;

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	this.readCookie = readCookie;

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

	this.eraseCookie = eraseCookie;

	function getLastIndex(adsname,adscount){
		var last_index = null;
		for(var i=0; i<adscount; i++){
			if(readCookie(adsname+'['+i+']') != null){
				last_index = readCookie(adsname+'['+i+']');
			}else{
				break;
			}
		}
		return last_index;
	}

	this.getLastIndex = getLastIndex;

	function close(){
		//set cookies for ads that have been displayed
		for(var i=0; i<session_ads_index_array.length; i++){
			createCookie(ads_name+'['+i+']',session_ads_index_array[i],0);
		}
	}

	this.close = close;
	
	function debug(array,other){
		var str = '';
		for(var i=0; i<array.length; i++){
			str += array[i] + '-';
		}
		if(manipclass == 'footer_ad')
			alert(str + ' other=' + other);
	}
}

var rotating_ads1 = new RotatingAds();
var rotating_ads2 = new RotatingAds();