var galleryObject = false;
var intervalID = 0;
var interval = 10000;
var intervalCount = 0;
var contextPath = "";
var loadInterval = false;
var next = false;
var previous = false;
var appHeight = 36;
var baseScroll = 0.3;
var addScroll = 0.1;
var hover = false;

var appNames = new Array();
var vendorNames = new Array();
var vendorIDs = new Array();
var contentIDs = new Array();
var featIconIDs = new Array();
var ratingCounts = new Array();
var ratings = new Array();
var localizedPrices = new Array();
var localizedFeatDescs = new Array();
var localizedContDescs = new Array();

var result= "";

function initSlideShow(){
	document.onmouseup = arrowUp;
	document.getElementById('featured_slideshow').onmouseout = arrowUp;
	document.getElementById('arrow_up').onmousedown = arrowPreviousDown;
	document.getElementById('arrow_down').onmousedown = arrowNextDown;
	
	galleryObject = document.getElementById('featuredapps');

	contextPath = document.getElementById('context').innerHTML;

	var divs = galleryObject.getElementsByTagName('div');
	for(var no=0;no<divs.length;no++){
		if(divs[no].className=='appName'){
			appNames[appNames.length] = divs[no].firstChild.title;
		}
		else if(divs[no].className=='vendorName'){
			vendorNames[vendorNames.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='vendorId'){
			vendorIDs[vendorIDs.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='contentID'){
			contentIDs[contentIDs.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='featIconID'){
			featIconIDs[featIconIDs.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='numRatings'){
			ratingCounts[ratingCounts.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='rating'){
			ratings[ratings.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='localizedPrice'){
			localizedPrices[localizedPrices.length] = divs[no].innerHTML;
		}
		else if(divs[no].className=='featDesc'){
			localizedFeatDescs[localizedFeatDescs.length] = divs[no].innerHTML.replace(/#N#/gi, '\n').replace(/&amp;/gi, '&');
		}
		else if(divs[no].className=='contDesc'){
			localizedContDescs[localizedContDescs.length] = divs[no].innerHTML.replace(/#N#/gi, '\n').replace(/&amp;/gi, '&');
		}
		else if(divs[no].id=='appsEnd')
			break;
	}

	intervalCount = Math.floor((contentIDs.length)*Math.random() + contentIDs.length);
	checkHeight();
	showPreview(intervalCount);
}

function downloadHover(e){
	if(!hover){
		hover = true;
		this.src = 'featured/img/get_details_hover.png';
	}
}

function downloadNoHover(){
	this.src = 'featured/img/get_details.png';
	hover = false;
}

function mPreview(index){
	oldApp = intervalCount;
	clearInterval(intervalID);
	if (intervalCount != index){
		intervalCount = index;
		if (!checkUp(oldApp) && !checkDown(oldApp)){
			slideToApp(oldApp, intervalCount);
		}
	}
}

function showPreview(index){
	index = index % contentIDs.length;
	
	var appName = fitStringToWidth(appNames[index], '226' , 'appNameJS');
	var vendorName = fitStringToWidthOneLine(byMessage + " " + vendorNames[index], '226' , 'largeCompDesc');
	
	document.getElementById('dataTable').style.opacity = 0;
	document.getElementById('largeFeatDesc').style.opacity = 0;
	document.getElementById('largeContDesc').style.opacity = 0;
	document.getElementById('morediv').style.opacity = 0;
	
	if (!document.getElementById('featIcon').src){
		//In IE6, the first time the page renders, the 'src' attribute of this image is undefined
		document.getElementById('imageLink').innerHTML = '<img id="featIcon" height="165" width="165" class="wspngfix" src="' + contextPath + '/servedimages/' + featIconId + '.png/?t=5" title="' + appNames[index] + '" alt="' + appNames[index] + '"/>';
	} else{
		//In IE7, FF, Opera, Chrome, and in IE6 after the first app switch, the 'src' attribute exists, so I just modify it
		var image = document.getElementById('featIcon');
		image.src = contextPath + '/servedimages/' + featIconIDs[index] + '.png/?t=5';
	}
	document.getElementById('imageLink').href = contextPath + '/content/' + contentIDs[index] + "/" + filterParams;	
	document.getElementById('imageLink').onclick = function(){homeNavigation('Appworld_Featured_Icon_' + appNames[index]);};
	document.getElementById('featIcon').title = appNames[index];
	document.getElementById('featIcon').alt = appNames[index];
	document.getElementById('largeAppLink').href = contextPath + '/content/' + contentIDs[index] + "/" + filterParams;
	document.getElementById('largeAppLink').title = appNames[index];
	document.getElementById('largeAppLink').innerHTML =  '<span class="appNameJS">' + appName + '</span>';
	document.getElementById('largeAppLink').onclick = function(){homeNavigation('Appworld_Featured_Title_' + appNames[index]);};
	document.getElementById('vendorLink').href = contextPath + '/vendor/' + vendorIDs[index] + "/" + filterParams;
	document.getElementById('vendorLink').title = vendorNames[index];
	document.getElementById('vendorLink').innerHTML = vendorName;
	document.getElementById('vendorLink').onclick = function(){homeNavigation('Appworld_Featured_Vendor_' + vendorNames[index]);};
	document.getElementById('todayButton1outputLink').href = contextPath + '/content/' + contentIDs[index] + "/" + filterParams;
	document.getElementById('todayButton1outputLink').onclick = function(){homeNavigation('Appworld_Featured_getDetailsButton_' + appNames[index]);};
	document.getElementById('largeRatingLink').href = contextPath + '/content/reviews/' + contentIDs[index] + "/" + filterParams;
	document.getElementById('largeRatingLink').innerHTML = ratingCounts[index];
	document.getElementById('largeRatingLink').onclick = function(){homeNavigation('Appworld_Featured_LargeRating_' + appNames[index]);};
	document.getElementById('starRating').src = contextPath + '/img/stars/star' + ratings[index] + '.png';
	document.getElementById('largePrice').innerHTML = localizedPrices[index];
	document.getElementById('largeFeatDesc').innerHTML = '<pre class="featuredDescsPre">' + localizedFeatDescs[index] + '</pre>';
	document.getElementById('largeContentDesc').value = localizedContDescs[index];
	document.getElementById('moreLink').href = contextPath + '/content/' + contentIDs[index] + "/" + filterParams;
	document.getElementById('moreLink').onclick = function(){homeNavigation('Appworld_Featured_more_' + appNames[index]);};
	

	new OpacityTween(document.getElementById('dataTable'),Tween.regularEaseIn, 0, 100, 0.3).start();
	new OpacityTween(document.getElementById('largeFeatDesc'),Tween.regularEaseIn, 0, 100, 0.3).start();
	new OpacityTween(document.getElementById('largeContDesc'),Tween.regularEaseIn, 0, 100, 0.3).start();
	if (document.getElementById('largeContentDesc').scrollHeight > (document.getElementById('largeContentDesc').offsetHeight + 13)){
		new OpacityTween(document.getElementById('morediv'),Tween.regularEaseIn, 0, 100, 0.3).start();
		document.getElementById('moreLink').style.display = 'block';
	}
	else{
		new OpacityTween(document.getElementById('morediv'),Tween.regularEaseIn, 0, 0, 0.3).start();
		document.getElementById('moreLink').style.display = 'none';
	}
}


function disableArrows(){
	document.getElementById('arrow_up').onmousedown = null;
	document.getElementById('arrow_down').onmousedown = null;
}

function enableArrows(){
	document.getElementById('arrow_up').onmousedown = arrowPreviousDown;
	document.getElementById('arrow_down').onmousedown = arrowNextDown;
}

function arrowNextDown(){
	clearInterval(intervalID);
	next = true;
	disableArrows();
	selectNextApp();
}

function selectNextApp(){
	var oldApp = intervalCount;
	intervalCount++;
	if (!checkDown(oldApp)){
		slideToApp(oldApp, intervalCount);
	}
}

function arrowPreviousDown(){
	clearInterval(intervalID);
	previous = true;
	disableArrows();
	selectPreviousApp();
}

function selectPreviousApp(){
	var oldApp = intervalCount;
	intervalCount--;
	if (!checkUp(oldApp)){
		slideToApp(oldApp, intervalCount);
	}
}

function arrowUp(){
	previous = false;
	next = false;
}

function slideToApp(fromApp, selectedApp){
	var newTop = 0;
	var time = 0;
	newTop = (selectedApp * -appHeight) + (3*appHeight);

	var diff = fromApp - selectedApp;
	if (diff != 0){
		if (diff < 0)
			diff = diff * -1;
		
		time = baseScroll + (diff - 1)* addScroll;
	}

	var autoTween = new Tween(galleryObject.style,'top',Tween.noneEaseInOut,galleryObject.offsetTop,newTop,time,'px');
	autoTween.onMotionFinished = function(){ checkSlide();};
	autoTween.start();
}

function checkHeight(){
	clearInterval(loadInterval);
	if (galleryObject.offsetHeight == 0)
		loadInterval = setInterval(checkHeight, 50);
	else{
		galleryObject.style.top = (intervalCount * -36) + 108 + 'px';
		intervalID = setInterval(selectNextApp, interval);
		testAll();
	}
}

function checkUp(oldApp){
	if (intervalCount < 4){
		var appDiff = oldApp - intervalCount;
		intervalCount = parseInt(intervalCount) + parseInt(contentIDs.length);
		galleryObject.style.top = ((intervalCount-3) * -appHeight) - (appDiff * appHeight) + 'px';
		var newTop = parseInt(galleryObject.offsetTop) + (appHeight*appDiff);
		var time = baseScroll + (addScroll * (appDiff-1));
		var tween = new Tween(galleryObject.style,'top',Tween.noneEaseInOut,galleryObject.offsetTop,newTop,time,'px');
		tween.onMotionFinished = function(){ checkSlide();};
		tween.start();
		return true;
	}
	return false;
}

function checkDown(oldApp){
	if (intervalCount > ((3*contentIDs.length)-5)){
		var appDiff = intervalCount - oldApp;
		intervalCount = intervalCount - contentIDs.length;
		galleryObject.style.top = ((intervalCount-3) * -appHeight) + (appDiff * appHeight) + 'px';
		var newTop = parseInt(galleryObject.offsetTop) - (appHeight*appDiff);
		var time = baseScroll + (addScroll * (appDiff-1));
		var tween = new Tween(galleryObject.style,'top',Tween.noneEaseInOut,galleryObject.offsetTop,newTop,time,'px');
		tween.onMotionFinished = function(){ checkSlide();};
		tween.start();
		return true;
	}
	return false;
}

function checkSlide(){
	if (next && !previous){
		selectNextApp();
	}
	else if (previous && !next){
		selectPreviousApp();
	}
	else{
		enableArrows();
		showPreview(intervalCount);
	}
}

function testAll(){
	for (var i = 0; i < contentIDs.length; i++){
		var label = document.getElementById(i).getElementsByTagName('div')[0].firstChild;
		if (label.offsetWidth > 166){
			document.getElementById(i).getElementsByTagName('label')[1].style.display = 'block';
			document.getElementById(i + contentIDs.length).getElementsByTagName('label')[1].style.display = 'block';
			document.getElementById(i + 2 * contentIDs.length).getElementsByTagName('label')[1].style.display = 'block';
		}
	}
}

function truncateAppSliderNames(){
	var featuredapps = document.getElementById('featuredapps');
	var allLabels = featuredapps.getElementsByTagName('label');	
	var numLabels = allLabels.length;
	var str = "";
	for (var i = 0; i < numLabels; i++){
		str = allLabels[i].innerHTML;
		if (str != null || str != ""){
			allLabels[i].innerHTML = fitStringToWidthOneLine(str,'160','sliderAppNameJS');
		}
	}	
	
}

truncateAppSliderNames();



function fitStringToWidthOneLine(str,width,className){
	// str    A string where html-entities are allowed but no tags.
	  // width  The maximum allowed width in pixels
	  // className  A CSS class name with the desired font-name and font-size. (optional)

	  //Create a span element that will be used to get the width
	  var span2 = document.createElement("span");
	  //Allow a classname to be set to get the right font-size.
	  if (className) span2.className=className;
	  span2.style.display='inline';
	  span2.style.visibility = 'hidden';
	  span2.style.padding = '0px';
	  document.body.appendChild(span2);
	  var result = str; 
	  span2.innerHTML = result;
	  
	  var lengthResult = result.length;
	  if(span2.offsetWidth > width){
		  while (span2.offsetWidth > width){
		  lengthResult--;
		  result = result.truncate(lengthResult, '');
		  span2.innerHTML = result;
		  }
		  result = result.truncate((lengthResult - 3), '');
		  result = result + '...';
	  }
	  document.body.removeChild(span2);
	  return result;
}

function fitStringToWidth(str,width,className) {
	  // str    A string where html-entities are allowed but no tags.
	  // width  The maximum allowed width in pixels
	  // className  A CSS class name with the desired font-name and font-size. (optional)

	  //Create a span element that will be used to get the width
	  var span = document.createElement("span");
	  //Allow a classname to be set to get the right font-size.
	  if (className) span.className=className;
	  span.style.display='inline';
	  span.style.visibility = 'hidden';
	  span.style.padding = '0px';
	  document.body.appendChild(span);
	  var result = str; 
	  span.innerHTML = result;

	  var lengthResult = result.length;
	  var length2 = result.length;
	  span.innerHTML = result;
	  var breakingtag = '&#8203;'
	  var result2 = result; 
	  // Check if the string will fit in the allowed width. NOTE: if the width
	  // can't be determined (offsetWidth==0) the whole string will be returned.
	  if(span.offsetWidth > width){
		  while (span.offsetWidth > width){
		  length2--;
		  result2 = result2.truncate(length2, '');
		  span.innerHTML = result2;
		  }
	 
		  var spaceInFirstLine = result2.lastIndexOf(" ");
		  var secondPartResult = "";
		  if (spaceInFirstLine < 0){
			  secondPartResult = result.substring(length2);
			  result = result2 +  breakingtag;
		  }	else {
			  secondPartResult = result.substring(spaceInFirstLine);
			  result = result2.substring(0, spaceInFirstLine);
		  }
		  
		  span.innerHTML = secondPartResult;
		  var lengthSecond = secondPartResult.length;
		  var thirdPartResult ="";
	  
		  if(span.offsetWidth > width){
			  var originalSecondPart = secondPartResult;
			  while (span.offsetWidth > (width)){
				  lengthSecond--;
				  
				  secondPartResult = secondPartResult.truncate(lengthSecond, '');
				  span.innerHTML = secondPartResult;
			  	}
			  var spaceInSecondLine = secondPartResult.lastIndexOf(" ");
			  if (spaceInSecondLine <= 0){
				  thirdPartResult =  originalSecondPart.substring(lengthSecond);
				  secondPartResult = secondPartResult + breakingtag;
			  } else {
				  secondPartResult = secondPartResult.substring(0, spaceInSecondLine);
				  thirdPartResult = originalSecondPart.substring(spaceInSecondLine);
			  }
		  }
		  result = result + secondPartResult;
		  span.innerHTML="...";
		  var dotsWidth = span.offsetWidth; 
		  
		  if(thirdPartResult.length > 0){
			  span.innerHTML = thirdPartResult;
			  var lengthThird = thirdPartResult.length;
			  if(span.offsetWidth > width){
				  while (span.offsetWidth > (width - dotsWidth)){
					  lengthThird--;
					  
					  thirdPartResult = thirdPartResult.truncate(lengthThird, '');
					  span.innerHTML = thirdPartResult;
				  	}
				  thirdPartResult = thirdPartResult + '...';
			  }
			  result = result + thirdPartResult;
		  }
	  }
	  document.body.removeChild(span);
	  return result;
	}


initSlideShow();

