var Accessories = function(selector, sectionId, siteId, preselect) {
  var accessories = this;
  
  accessories._div = $(selector);
  accessories._sectionId = sectionId;
  accessories._siteId = siteId;
  accessories._xmlURL = '/toyota/accessories/xml/accessories_' + accessories._siteId + '_' + accessories._sectionId + '.xml';
  accessories._imageIndex = 0;
  accessories._imageGroups = Array();

  $.ajax({
    url: accessories._xmlURL,
    dataType: 'xml',
    async: true,
    error: function() { },
    success: accessories._callback,
    accessoriesObject: accessories,
	preselectImage: preselect
  });
  
  var docHeight;
  var pageHeight = document.documentElement.clientHeight;
  
  if (document.compatMode && document.compatMode != 'BackCompat') {
    docHeight = document.documentElement.scrollHeight;
  } else if (document.body && typeof document.body.scrollHeight != 'undefined') {
    docHeight = document.body.scrollHeight;
  }
  
  if (docHeight < pageHeight) {
    docHeight = pageHeight;
  }
  
  if (navigator.appName == 'Microsoft Internet Explorer'){
    position = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
  } else {
    position = window.pageYOffset;
  }
  
  // Find the height of the viewport
  var viewPortHeight = self.innerHeight || ( document.documentElement && document.documentElement.clientHeight ) || document.body.clientHeight;
  if (viewPortHeight > pageHeight) {
    accessories._div.find('.black-overlay').css({height: 100+'%', opacity: .80});
  } else {
    accessories._div.find('.black-overlay').css({height: docHeight+'px', opacity: .80});
  }
  
  accessories._div.find('.controller .btn-prev a').click(function() {
    accessories._prevImage();
    return false;
  });
  accessories._div.find('.controller .btn-next a').click(function() {
    accessories._nextImage();
    return false;
  });
  accessories._div.find('.mainImage a, .btn-enlarge a').click(function() {
    accessories._setPopupMode(true);
    return false;
  });
  accessories._div.find('.btn-close, .btn-close a').click(function() {
    accessories._setPopupMode(false);
    return false;
  });
}

Accessories.prototype._callback = function(data, textStatus) {
  var accessories = this.accessoriesObject;
  var preselectImage = Number(this.preselectImage);
  if(isNaN(preselectImage) || preselectImage < 0) preselectImage = 0;

  accessories._imageGroups = Array();
  var prefix = 'acc\\:';
  var items = $(data).find(prefix + 'item');
  if(items.length == 0) {
    prefix = '';
    items = $(data).find(prefix + 'item');
  }
  $(items).each(function(i,n) {
    accessories._imageGroups[i] = Array();
    accessories._imageGroups[i].images = Array();
    accessories._imageGroups[i].label = $(n).find(prefix + 'label').text();
    accessories._imageGroups[i].title = $(n).find(prefix + 'descriptionTitle').text();
    accessories._imageGroups[i].body = $(n).find(prefix + 'descriptionBody').text();
    accessories._imageGroups[i].promotion = $(n).find(prefix + 'promotion').text();
    accessories._imageGroups[i].images.thumb = $(n).find(prefix + 'images').find(prefix + 'thumb').text();
    accessories._imageGroups[i].images.large = $(n).find(prefix + 'images').find(prefix + 'large').text();
    accessories._imageGroups[i].images.extraLarge = $(n).find(prefix + 'images').find(prefix + 'extraLarge').text();
  });
  
  accessories._div.find('.thumbnails').empty();
  for(var i=0; i < accessories._imageGroups.length; i++)
  {
    var thumbHTML = String();
    thumbHTML += '<a href="#" class="linkImg" rel="' + i + '">';
    thumbHTML += '<img src="' + accessories._imageGroups[i].images.thumb + '" alt="' + accessories._imageGroups[i].label + '" border=0 class="imgBox" />';
    thumbHTML += '</a>';
    accessories._div.find('.thumbnails').append(thumbHTML);
  }
  
  GlossaryTips_initGlobal();
  
  accessories._div.find('.thumbnails a.linkImg').each(function(i,n) {
    $(n).click(function() {
      accessories._changeImage( $(n).attr('rel') );
      accessories._imageIndex = Number($(n).attr('rel'));
      return false;
    });
  });
  
  accessories._changeImage(preselectImage);
}

Accessories.prototype._changeImage = function(imageIndex) {
  var accessories = this;
  if(accessories._imageGroups.length <= imageIndex) return;

  accessories._div.find('.thumbnails a').attr('class', 'linkImg');
  accessories._div.find('.thumbnails a[rel="' + imageIndex + '"]').attr('class', 'linkImgSelected');
  accessories._div.find('.sideInfo').html(accessories._imageGroups[imageIndex].title);
  accessories._div.find('.sideInfoDescription dd').html(accessories._imageGroups[imageIndex].body);
  
  accessories._div.find('.mainImage img').attr('src', accessories._imageGroups[imageIndex].images.large);
  accessories._div.find('.mainImage img').attr('alt', accessories._imageGroups[imageIndex].label);
}

Accessories.prototype._nextImage = function() {
  var accessories = this;
  accessories._imageIndex++;
  if(accessories._imageIndex >= accessories._imageGroups.length) accessories._imageIndex = 0;
  accessories._changeImage( accessories._imageIndex );
}

Accessories.prototype._prevImage = function() {
  var accessories = this;
  accessories._imageIndex--;
  if(accessories._imageIndex < 0) accessories._imageIndex = accessories._imageGroups.length - 1;
  accessories._changeImage( accessories._imageIndex );
}

Accessories.prototype._setPopupMode = function(mode) {
  var accessories = this;
  
  if(mode) {
    /*accessories._div.find('.gp_main_image img').attr('src', accessories._imageGroups[accessories._imageIndex].images.extraLarge);
    accessories._div.find('.gp_main_image img').attr('alt', accessories._imageGroups[accessories._imageIndex].label);*/
    accessories._div.find('.popupImage img').attr('src', accessories._imageGroups[accessories._imageIndex].images.extraLarge);
    accessories._div.find('.popupImage img').attr('alt', accessories._imageGroups[accessories._imageIndex].label);
    
    var popupDiv = accessories._div.find('.gallery_popup');
    var containerHeight = $(window).height();
    var containerWidth = $('.container_main').width();
    var popupHeight = popupDiv.height();
    var popupWidth = popupDiv.width();
    popupDiv.css('position','absolute');
    popupDiv.css('top', ( containerHeight - popupHeight ) / 2 + $(window).scrollTop() + 'px');
    popupDiv.css('left', ( containerWidth - popupWidth ) / 2 + $(window).scrollLeft() + 'px');

    accessories._div.find('.black_overlay').fadeIn('slow');
    accessories._div.find('.gallery_popup').fadeIn('slow');
  }
  else {
    accessories._div.find('.black_overlay').fadeOut('slow');
    accessories._div.find('.gallery_popup').fadeOut('slow');
  }
}

/*
 * Focus Vehicles - Media Gallery thumbnails tooltips
 * By Ronald Jusuf
 * Hothouse 2009
 */
 
function GlossaryTips_initGlobal() {
	
	$('.thumbnails-gallery a').each(function(i,n){	
		$(n).hover(function(e){
			var hoveredThumbId = $(this).attr('rel');
			var altText = $(this).find('.imgBox').attr('alt');
			
			$(this).attr('id','thumb'+hoveredThumbId);
			var linkXCoord = getAbsoluteLeft(hoveredThumbId);
			var hoveredPos = getHoverPos(hoveredThumbId); //looking for 'left''middle''right'
			
			if(hoveredPos == 'middle'){
				linkXCoord -= 56;
			}else if(hoveredPos == 'right'){
				linkXCoord -= 113;
			}
			
			var thumbPopupStruc;
			thumbPopupStruc = "<div class=\"thumb_description_popup "+hoveredPos+"\">";
			thumbPopupStruc += "<div class=\"thumb_description_container\">";
			thumbPopupStruc += "<div class=\"summary\">";
			thumbPopupStruc += "<div class=\"glossary_text\">"+altText;
			thumbPopupStruc += "</div></div></div></div>";
			
			/*$('.thumb_description_popup.'+hoveredPos+' .glossary_text').text(altText);*/
			
			$('body').prepend(thumbPopupStruc);
			$('.thumb_description_popup').css('display','block');
			var topCoordinate = getAbsoluteTop(hoveredThumbId);
			var mainContainerHeight = $('.thumb_description_popup .thumb_description_container').height();
			var linkYCoord = topCoordinate - mainContainerHeight;
			$('.thumb_description_popup').css({left:linkXCoord+'px', top:linkYCoord+'px'});
					
		}, function(){
			$('.thumb_description_popup').css('display','none');
			$('.thumb_description_popup').remove();
		});
	});
}

function getHoverPos(linkIndex){
	var numberLinks = ($('.thumbnails-gallery a').length)-1;
	var leftLinks = new Array();
	var middleLinks = new Array();
	var rightLinks = new Array();
	
	var leftLinksIndex = 0;
	var counter = 0;
	
	for(var i=0; i<=numberLinks; i++){
		if(counter < 3){
			leftLinks[i] = leftLinksIndex;
			leftLinksIndex++;
			counter++;
		}else if(counter == 3){
			counter = 0;
			leftLinksIndex += 5;
		}
	}
	
	var middleLinksIndex = 3;
	var counter = 0;
	
	for(var i=0; i<=numberLinks; i++){
		if(counter < 2){
			middleLinks[i] = middleLinksIndex;
			middleLinksIndex++;
			counter++;
		}else if(counter == 2){
			counter = 0;
			middleLinksIndex += 6;
		}
	}
	
	var rightLinksIndex = 5;
	var counter = 0;
	
	for(var i=0; i<=numberLinks; i++){
		if(counter < 3){
			rightLinks[i] = rightLinksIndex;
			rightLinksIndex++;
			counter++;
		}else if(counter == 3){
			counter = 0;
			rightLinksIndex += 5;
		}
	}
	
	for(var i=0; i<=leftLinks.length; i++){
		if(linkIndex == leftLinks[i]){
			return 'left';
		}
	}
	
	for(var i=0; i<=middleLinks.length; i++){
		if(linkIndex == middleLinks[i]){
			return 'middle';
		}
	}
	
	for(var i=0; i<=rightLinks.length; i++){
		if(linkIndex == rightLinks[i]){
			return 'right';
		}
	}
	
}


function getAbsoluteLeft(linkId) {
	var xCoord = 0;
	var hoveredThumb = document.getElementById('thumb'+linkId);
	xCoord = hoveredThumb.offsetLeft;
	oParent = hoveredThumb.offsetParent;
	while(oParent!= null) { //IE only takes the direct parent, needs to loop to the outer most parent
		xCoord += oParent.offsetLeft;
		oParent = oParent.offsetParent;
	}
	return xCoord;
}

function getAbsoluteTop(linkId) {
	var yCoord = 0;
	var hoveredThumb = document.getElementById('thumb'+linkId);
	yCoord = hoveredThumb.offsetTop;
	oParent = hoveredThumb.offsetParent;
	while(oParent!= null) {//IE only takes the direct parent, needs to loop to the outer most parent
		yCoord += oParent.offsetTop;
		oParent = oParent.offsetParent;
	}
	return yCoord;
}

function getPositionType(hoveredIndex){
	var linksLength = ($('.thumbnails a').length)-1;
}
