

/**
 * @constructor
 * @param {string} id: identifier for your advertisement space
 * @param {string} mode: 'REFRESH' or 'ROTATE'
 */
function AdSpace( id, mode ) {
	this._id = id;
	this._mode = mode;
	this._Ads = new Array();
	this._current = -1;
}

/**
 * loads advertisement datas from a XML file
 *
 * file example can be found at the bottom ?!
 *
 * @param {string} filepath: the relative path of the XML file
 */
AdSpace.prototype.loadXMLFile = function( fpath ) {
  if (window.XMLHttpRequest) {
    xhttp=new XMLHttpRequest();
  }
  else { // Internet Explorer 5/6
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.open("GET",fpath,false);
  xhttp.send(null);
  xmlDoc = xhttp.responseXML;

  if (xhttp.status != 200){
	  return false;
  }

  var x = xmlDoc.getElementsByTagName("ad");
  for (var i = 0 ; i < x.length ; i++ ) {
	  var Ad = { extension: null, file: null, width: null, height: null, link: null, alt: null, begin: null, end: null, duration: null };
	  Ad.extension = x[i].getElementsByTagName("ext")[0].childNodes[0].nodeValue;
	  Ad.file = x[i].getElementsByTagName("f")[0].childNodes[0].nodeValue;
	  Ad.width = x[i].getElementsByTagName("w")[0].childNodes[0].nodeValue;
	  Ad.height = x[i].getElementsByTagName("h")[0].childNodes[0].nodeValue;
	  Ad.link = x[i].getElementsByTagName("lnk")[0].childNodes[0].nodeValue;
	  Ad.alt = x[i].getElementsByTagName("alt")[0].childNodes[0].nodeValue;
	  Ad.begin = x[i].getElementsByTagName("beg")[0].childNodes[0].nodeValue;
	  Ad.end = x[i].getElementsByTagName("end")[0].childNodes[0].nodeValue;
	  Ad.duration = x[i].getElementsByTagName("dur")[0].childNodes[0].nodeValue;
	  this._Ads.push(Ad);
  }
  return true;
}

/**
 * loads advertisement datas from a JSON file
 *
 * file example can be found at the bottom ?!
 *
 * @param {string} filepath: the relative path of the JSON file
 */
AdSpace.prototype.loadJSONFile = function( fpath ) {
  if (window.XMLHttpRequest) {
    xhttp=new XMLHttpRequest();
  }
  else { // Internet Explorer 5/6
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.open("GET",fpath,false);
  xhttp.send(null);

  if (xhttp.status != 200){
	  return false;
  }
  var JSONparsing = eval('('+xhttp.responseText+')');
  this._Ads = JSONparsing.ads;
  return true;
}

/**
 * adds a banner to your Advertisement Space
 *
 * file example can be found at the bottom ?!
 *
 * @param {string} extension: 'SWF', 'PNG', JPEG', 'GIF'
 * @param {string} filepath: the relative path of your banner on the website
 * @param {integer} width: the width (in pixel) of your banner
 * @param {integer} height: the height (in pixel) of your banner
 * @param {string} link: URL of the website target of the advertisement
 * @param {string} alt: alternative text for the banner
 * @param {string} begin: the start date you want your banner to show up on your website - french format: 'JJ/MM/AAAA'
 * @param {string} end: the date the advertisement must end - french format 'JJ/MM/AAAA' or 'NEVER'
 * @param {integer} duration: for the ROTATE mode. Time your banner must be displayed before switching to the next. in ms.
 */
AdSpace.prototype.addBanner = function ( extension, filepath, width, height, link, alt, begin, end, duration ) {
	  if (typeof duration == 'undefined') duration = 0;  
	  if (duration == 'NONE') duration = 0;
	  var Ad = { extension: null, file: null, width: null, height: null, link: null, alt: null, begin: null, end: null, duration: null };
	  Ad.extension = extension;
	  Ad.file = filepath;
	  Ad.width = width;
	  Ad.height = height;
	  Ad.link = link;
	  Ad.alt = alt;
	  Ad.begin = begin;
	  Ad.end = end;
	  Ad.duration = duration;
	  this._Ads.push(Ad);
}

AdSpace.prototype.toHTML = function () {
	var HTMLtext = '';

	HTMLtext += '<span id="'+this._id+'">';
	switch(this._mode) {
		case 'REFRESH':
			do {
				this._current = rand( this._Ads.length );
//				alert('toHTML() :: this._current: '+this._current);
			} while( !this.isReadyForAdvertising(this._current) );
			HTMLtext += this.getELEMENT(this._current);
			break;
		case 'ROTATE':
			for (var i = 0 ; i < this._Ads.length ; i++ ){
				HTMLtext += '<span id="'+this._id+'_'+i+'" style="display:none;">';
				HTMLtext += this.getELEMENT(i);
				HTMLtext += '</span>';
			}
			break;
	}
	HTMLtext += '</span>';

	return HTMLtext;
}

AdSpace.prototype.start = function () {
	var waiting = 0;
	var next = -1;

//	alert('start() :: this._Ads.length: '+this._Ads.length);
	if (this._mode == 'ROTATE') {
		next = this.next( this._current );
//		alert('start() :: current: '+this._current+' :: next: '+next);
		if ( next != -1 ) {
			waiting =  this._Ads[next].duration;
			if ( this._current != -1 ) {
				this.hide( this._current );
			}
			this.show( next );
			this._current = next;

			setTimeout(this._id+'.start()',waiting);
		}
	}
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

AdSpace.prototype.next = function ( ind ) {
  var indFound = -1;

  for (var i = ind+1 ; i <  this._Ads.length ; i++ ) {
	  if (this.isReadyForAdvertising ( i )){
		  indFound = i;
		  break;
	  }
  }
  if (indFound < 0) {
	for (var j = 0 ; j < ind ; j++ ){
		if (this.isReadyForAdvertising ( j )){
			indFound = j;
			break;
		}
	}
  }
  return indFound;
}

AdSpace.prototype.show = function ( ind ) {
	var ID = ''+this._id+'_'+ind;
//	alert('show() :: ID: '+ID);
	if (this.isReadyForAdvertising( ind )) {
		$(ID).style.display = "";
	}
}

AdSpace.prototype.hide = function ( ind ) {
	if (typeof ind == 'undefined') {
		for (var ind = 0 ; ind < this._Ads.length ; ind++ ){
			var ID = ''+this._id+'_'+ind;
//			alert('hide() :: ID: '+ID);
			if (this.isReadyForAdvertising( ind )) {
				$(ID).style.display = "none";
			}
		}
	} else {
		var ID = ''+this._id+'_'+ind;
//		alert('hide() :: ID: '+ID);
		$(ID).style.display = "none";
	}
}

AdSpace.prototype.isReadyForAdvertising = function ( ind ) {
	var isReady = true;
	var today = new Date();

	if (this.isValid( ind )) {

		var beginTbl = this._Ads[ind].begin.split('/');
		var beginDate = new Date();
		beginDate.setFullYear(parseInt(beginTbl[2]),parseInt(beginTbl[1])-1,parseInt(beginTbl[0]));

		if (today < beginDate){
			isReady = false;
		} else {
			if (this._Ads[ind].end != 'NEVER') {
				var endTbl = this._Ads[ind].end.split('/');
				var endDate = new Date();
				endDate.setFullYear(parseInt(endTbl[2]),parseInt(endTbl[1])-1,parseInt(endTbl[0]));

				if (today > endDate) {
					isReady = false;
				}
			}
		}
	} else {
		isReady = false;
	}

//	alert('isReadyForAdvertising() :: ind: '+ind+' :: isReady: '+isReady);
	return isReady;
}

AdSpace.prototype.isValid = function ( ind ) {
	var isValid = false;
	var cptValid = 0;
	var numeric = new RegExp("^[0-9]+$");
	var frenchDate = new RegExp("^[0|1|2|3]{0,1}?[0-9]/[0|1]{0,1}?[0-9]/[2|3|4|5|6|7|8|9][0-9]{3}$");
	var frenchExceptionOne = new RegExp("^[|0]0/[0-9]{1,2}/[0-9]{4}$");
	var frenchExceptionTwo = new RegExp("^[0-9]{1,2}/[|0]0/[0-9]{4}$");

	switch(this._Ads[ind].extension) {
		case "SWF":
		case "swf":
		case "PNG":
		case "png":
		case "JPEG":
		case "jpeg":
		case "GIF":
		case "gif":
		case "JPG":
		case "jpg":
			cptValid ++;
			break;
	}

	if (this._Ads[ind].file != null && this._Ads[ind].file != '') {
		cptValid++;
	}

	if (this._Ads[ind].width != null && this._Ads[ind].width != '' && numeric.test(this._Ads[ind].width)) {
		cptValid++;
	}

	if (this._Ads[ind].height != null && this._Ads[ind].height != '' && numeric.test(this._Ads[ind].height)) {
		cptValid++;
	}

	if (this._Ads[ind].begin != null && this._Ads[ind].begin != '' && (frenchDate.test(this._Ads[ind].begin) && (!frenchExceptionOne.test(this._Ads[ind].begin)) && (!frenchExceptionTwo.test(this._Ads[ind].begin)))) {
		cptValid++;
	}

	if (this._Ads[ind].end != null && this._Ads[ind].end != '' && (this._Ads[ind].end == 'NEVER' || (frenchDate.test(this._Ads[ind].end) && (!frenchExceptionOne.test(this._Ads[ind].end)) && (!frenchExceptionTwo.test(this._Ads[ind].end))))) {
		cptValid++;
	}

	if (cptValid == 6) {
		isValid = true;
	}

//	alert('isValid() :: ind: '+ind+' :: isValid: '+isValid);
	return isValid; 
}

AdSpace.prototype.getELEMENT = function ( ind ) {
			switch(this._Ads[ind].extension){
				case 'SWF':
				case 'swf':
					return this.getFLASH( ind );
					break;
				default:
					return this.getIMAGE( ind );
					break;
			}
}

AdSpace.prototype.getFLASH = function ( ind ) {
	var flashString = '';

	if (this._Ads[ind].link != '' && this._Ads[ind].link != null){
		flashString += '<a href="'+this._Ads[ind].link+'" target="_blank">'
	}
	flashString += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
	flashString += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" ';
	flashString += 'width="'+this._Ads[ind].width+'" ';
	flashString += 'height="'+this._Ads[ind].height+'" ';
	flashString += 'id="FLASH_'+ind+'" ';
	flashString += 'align="middle">';
	flashString += '<param name="allowScriptAccess" value="sameDomain" />';
	flashString += '<param name="allowFullScreen" value="false" />';
	flashString += '<param name="movie" value="'+this._Ads[ind].file+'" />';
	flashString += '<param name="quality" value="high" />';
	flashString += '<param name="bgcolor" value="#ffffff" />';	

	flashString += '<embed src="'+this._Ads[ind].file+'" ';
	flashString += 'quality="high" ';
	flashString += 'bgcolor="#ffffff" ';
	flashString += 'width="'+this._Ads[ind].width+'" ';
	flashString += 'height="'+this._Ads[ind].height+'" ';
	flashString += 'name="FLASH_'+ind+'" ';
	flashString += 'align="middle" ';
	flashString += 'allowScriptAccess="sameDomain" ';
	flashString += 'allowFullScreen="false" ';
	flashString += 'type="application/x-shockwave-flash" ';
	flashString += 'pluginspage="http://www.adobe.com/go/getflashplayer_fr" />';

	flashString += '</object>';
	if (this._Ads[ind].link != '' && this._Ads[ind].link != null){
		flashString += '</a>'
	}

	return flashString;
}

AdSpace.prototype.getIMAGE = function ( ind ) {
	var imageString = '';

	if (this._Ads[ind].link != '' && this._Ads[ind].link != null){
		imageString += '<a href="'+this._Ads[ind].link+'" target="_blank">'
	}
	imageString += '<img src="'+this._Ads[ind].file+'" ';
	imageString += 'width="'+this._Ads[ind].width+'" ';
	imageString += 'height="'+this._Ads[ind].height+'" ';
	if (this._Ads[ind].alt != '' && this._Ads[ind].alt != null) {
		imageString += 'alt="'+this._Ads[ind].alt+'" ';
	}
	imageString += 'border="0">';
	if (this._Ads[ind].link != '' && this._Ads[ind].link != null){
		imageString += '</a>'
	}

	return imageString;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

function log10 ( val ) {
	return (Math.log(val)/Math.log(10));
}

function rand ( val ) {
	return parseInt((Math.random()*(Math.pow((1 + log10(val)),10))) % val);
}

function $(id) {
	elt = document.getElementById ? document.getElementById(id) : document.all ? document.all[id] : null
	return elt;
}

