var iNoOfPics = aImgUrls.length;
var IE = /*@cc_on!@*/false;
var iMinWait = 3000; //minimum time in miliseconds before next flip
var iWaitVariance = 3000; //Variance in miliseconds between flips (SO: possible time flipping range is from iMinWait until iMinWait+iWaitVariance)
var ifadeTime = 1400; //duration of fading process in miliseconds
var iNoOfEls = 5; //no of Elements


function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function inTopRefFields(valueToCheck) //returns true if a reference with the same customer is already shown on the page
{
	var sCustomerOfReferenceToCheck = trim(aImgUrls[valueToCheck]["Url"]);
	sCustomerOfReferenceToCheck = '/files/' + sCustomerOfReferenceToCheck;
	for (iVaFi=0; iVaFi < iNoOfEls; iVaFi++)
	{
		var iIVaFiOne = iVaFi+1;
		var sTitleOfTarget = aUsedTitles[iIVaFiOne];
		var iCheckStringSpot = sTitleOfTarget.indexOf("|");
		iCheckStringSpot+=3;
		var sCheckStringOfExistingElement = sTitleOfTarget;
//	        alert("comparing: " + sCheckStringOfExistingElement + "\nto: " + sCustomerOfReferenceToCheck);
		sCheckStringOfExistingElement = trim(sCheckStringOfExistingElement);
		if (sCheckStringOfExistingElement == sCustomerOfReferenceToCheck) {
					return true;}
	}
	return false;
}

function randomizeMe () { //find random id of which the customer is not used yet
	var randomRefId=(Math.floor(Math.random()*iNoOfPics));
	while (inTopRefFields(randomRefId)) {
		randomRefId = (Math.floor(Math.random()*iNoOfPics)); 
	}
	return randomRefId;
}

function changeHrefAttr(iSpot, sNewHref) {
  oOldSpot = jQuery("#TopRef"+iSpot+" a");
  jQuery(oOldSpot).attr("href", sNewHref);
}

function fadeImageLater(iSpot, sNewPath, sAssembledTitle, sNewHref) {
	//get objects of a element and img element
//	oOldSpot = jQuery("#TopRef"+iSpot+" a");
	oOldSpotImg = jQuery("#TopRef"+iSpot+" a img");
	//hide img (background has been set before)
	jQuery(oOldSpotImg).css("display", "none");
	//change image src
	jQuery(oOldSpotImg).attr("src", sNewPath);
	//initialize new tooltip
	oOldSpotImg.attr("title", sAssembledTitle);
	oOldSpotImg.tooltip({id: "DotTip",track: true,delay: 0,showURL: false,showBody: " || ",extraClass: "pretty",top: -5,left: 14});
	//change a href after halfly fading pics
	setTimeout("changeHrefAttr(" + iSpot + ",'" + sNewHref + "')", ifadeTime/2);
	jQuery(oOldSpotImg).fadeIn(ifadeTime);
}

function fadeFlipImage(iSpot, sNewPath, sAssembledTitle, sNewHref) {
	//get source of old img and object for replacement
	sOldSpotImgSrc = jQuery("#TopRef"+iSpot+" a img").attr("src");
	oOldSpot = jQuery("#TopRef"+iSpot);
	//set old Image as background-image of list element
	jQuery(oOldSpot).css("background-image","url(" + sOldSpotImgSrc + ")");
	//to avoid flickering on exchanging the pics, flip is initiated after a short timeout
	setTimeout("fadeImageLater("+ iSpot +", '"+ sNewPath +"', '"+ sAssembledTitle +"', '"+ sNewHref +"')",250);
}


function flipRandomPic(lastRandomSpot) {
	//avoid the successional flipping at the same spot and find a random spot to flip
	var randomSpot=lastRandomSpot;
	while (randomSpot == lastRandomSpot) {randomSpot = (Math.floor(Math.random()*iNoOfEls)+1);}
	//get Random Id of reference that is not already showing
	var iRefId = randomizeMe();
	//assemble path of new picture
	var sNewPath = "/files/"+aImgUrls[iRefId]["Url"];
	// write new src into cookie
	document.cookie = "src" + randomSpot + "=" + sNewPath;
	//assemble new title and put into "used" array
	var sAssembledTitle = aImgUrls[iRefId]["Name"] + " || " + aImgUrls[iRefId]["Customer"];
	var sNewHref = aImgUrls[iRefId]["UrlOfArticle"];
	aUsedTitles[randomSpot] = sNewPath;
	//create new image object to preload flip-image
	var oNewImage = new Image();
	oNewImage.onload = function(){ fadeFlipImage(randomSpot, sNewPath, sAssembledTitle, sNewHref); }
	oNewImage.src = sNewPath;
	//initiate new flip 
	var randomTime = (Math.floor(Math.random()*iWaitVariance)+iMinWait);
	setTimeout("flipRandomPic(" + randomSpot + ")", randomTime);
}


jQuery(document).ready(function(){
//generate random variables upon load
var randomTimeInit = (Math.floor(Math.random()*(iWaitVariance/2))+500);
var randomSpotInit = (Math.floor(Math.random()*iNoOfEls)+1);

//hand over used titles into array
aUsedTitles = new Array();

//set a cookie
var date = new Date;
date.setMonth(date.getMinutes()+15);
document.cookie = "thisCookie=dotflyReferenceFaderCookie; expires=" + date.toGMTString();

////tell aUsedTitlesArray (which actually is the used SRC Array) which srcs are used.
////Title was used formlerly to ensure uniqueness of customer, now only uniqueness of pic is checked via src attribute
////Also hand this data over to cookie
if (document.cookie !="") {
  for (iInit=1; iInit<=iNoOfEls; iInit++) {
	//get beginning of string in cookie
	var iBeginningOfSrc = document.cookie.indexOf("src"+iInit);
	//get end of string in cookie
	var sSliceStringOfSrc = document.cookie.slice(iBeginningOfSrc);
	var iEndOfSrc;
	var iWhitespaceCheck = sSliceStringOfSrc.indexOf(" ");
//	alert(iWhitespaceCheck);
//	alert(sSliceStringOfSrc.slice(0,iWhitespaceCheck));
//	(iWhitespaceCheck != -1) ? iEndOfSrc = sSliceStringOfSrc.length : iEndOfSrc = ((sSliceStringOfSrc.indexOf(' '))+1);
	var iEndOfSrc = sSliceStringOfSrc.indexOf(";");
//	alert(iEndOfSrc);
	var sSrcString = sSliceStringOfSrc.slice(0, iEndOfSrc);
	//alert(sSrcString);
	var sTitleUsed = jQuery("#TopRef" + iInit + " a img").attr("src");
	aUsedTitles[iInit] = sTitleUsed;
  }
}
else {
  for (iInit=1; iInit<=iNoOfEls; iInit++) {
	var sTitleUsed = jQuery("#TopRef" + iInit + " a img").attr("src");
	aUsedTitles[iInit] = sTitleUsed;
	document.cookie = "src" + iInit + "=" + sTitleUsed;
  }
}

//apply tooltip to fields
jQuery('#TopReferences li a img').tooltip({
		id: "DotTip",
		track: true,
		delay: 0,
		showURL: false,
		showBody: " || ",
		extraClass: "pretty",
		top: -5,
		left: 14
});

//fire flip function first time
setTimeout("flipRandomPic(" + randomSpotInit + ")",randomTimeInit);
});