var sketchUpImageArray = new Array();
var currentPos = 0;
var addToPos = 0;
var imageCount = 0;

var sketchUpObj = null;

var mouseXOrig;
var mouseX = 0;
var mouseY = 0;
var mouseIsDown = false;

var title = null;
var amountOfPics = 11 //this sets the number of pics shown for other views


     function getARSImages(newSku,bookMark)
{
    {
    //alert(newSku);
    var xmlDoc;
	
	var xReq = createXMLHttpRequest();	
		  	
	    xReq.open("GET", "content/ajax.getOtherViews.asp?newSku=" + newSku);	
	  
	    xReq.onreadystatechange = function() {
		if (xReq.readyState != 4)  { return; }
			
	  	xmlDoc = importXML(xReq.responseText);
        
	  	var newAttributeID;

        if(window.ActiveXObject)
        {
            itemNodes = xmlDoc.selectNodes("/products/product");
        }
        else
        {
           itemNodes = xmlDoc.getElementsByTagName('product');
        }
        
        if (itemNodes.length > amountOfPics)
        {
            var pics = new Array(itemNodes.length);   
                
            for(var p = 0; p < itemNodes.length; p++) {pics[p] = new Array(4)};
            for (var b = 0; b < itemNodes.length; b++)
            {
                
                pics[b] = [(itemNodes[b].attributes[0]).value,(itemNodes[b].attributes[1]).value,(itemNodes[b].attributes[2]).value,(itemNodes[b].attributes[3]).value,(itemNodes[b].attributes[4]).value];
           
                
            }
            var bookMarkCount = amountOfPics;
        }
        else
        {
            
            var pics = new Array(itemNodes.length);
                
            for(var p = 0; p < itemNodes.length; p++) {pics[p] = new Array(4)};
            for (var b = 0; b < itemNodes.length; b++)
            {
                pics[b] = [(itemNodes[b].attributes[0]).value,(itemNodes[b].attributes[1]).value,(itemNodes[b].attributes[2]).value,(itemNodes[b].attributes[3]).value,(itemNodes[b].attributes[4]).value];
                
            }
            var bookMarkCount = itemNodes.length
        }

        var loopCount = 0;
        var startLoop = bookMark;  //this var needs to be set onclick from the arrows right or left
        
        for(var s = startLoop; s < bookMark+bookMarkCount; s++)
		    {  
			    //alert(itemNodes[0].firstChild.nodeValue);		
			    //var imagePath = (itemNodes[s].attributes[0]).value
			    //var newsku = (itemNodes[s].attributes[1]).value;
			    //var item_number = (itemNodes[s].attributes[2]).value;
			    //alert(imagePath + '----' + newsku);
			    //alert(bookMarkCount);
			    
			    var imagePath = pics[s][0];
		        //var fileName = pics[s][1];
		        var item_number = pics[s][2];
		        var newsku = pics[s][1];
		        var interactive = pics[s][3];
		        var roomView = pics[s][4];
                    
		        var cellCount = s;
               
			    buildOtherViewCells(imagePath,newsku,item_number,cellCount,itemNodes.length,startLoop, interactive, roomView);
            //addCategoryRow('categoryListTable',attributeName,newAttributeID); 
            }
		};
                  
        xReq.send(null);
 }
}
function hideInteractiveDiv()
{	
    var divs = document.getElementById('divShowing').value;
    //alert(document.getElementById('divShowing').value);
        
    if(divs == 1) 
    {
    var wrapper = document.getElementById("wrapper");
    var intDiv = document.getElementById("interactive");
       wrapper.removeChild(intDiv);
    divs.value = 0;
    document.getElementById('divShowing').value = 0;
    }
}
var fileString = '';




function init(newSku) 
{

  var xmlDoc2;
         	
     var intNumber;
     var intName;
     var fileString = "";
     
	 var xReq2 = createXMLHttpRequest(); 
	 xReq2.open("GET", "./content/ajax.getInteractiveProduct.asp?newSku=" + newSku);

    xReq2.onreadystatechange = function() 
    {
	    if (xReq2.readyState != 4)  { return; }
			
  	    xmlDoc2 = importXML(xReq2.responseText);
        
  	    

        if(window.ActiveXObject)
        {
            itemNodes2 = xmlDoc2.selectNodes("intPictures/intPicture");
        }
        else
        {
            itemNodes2 = xmlDoc2.getElementsByTagName('intPicture');
        }
        
         intNumber = (itemNodes2[0].attributes[0].value);
         intName = (itemNodes2[0].attributes[1].value);
         //alert(intNumber);
           
		 

        //alert(intName);


         for(i = 0; i < intNumber-1; i++)
        {
           
             fileString = fileString + intName + "_image" + i + ".jpg,";
           //  alert(intName + "_image" + i + ".jpg,";);
        }
        fileString = fileString + intName + "_image" + (i+1) + ".jpg";


        imageFileNameArray = fileString.split(",");
        //alert(imageFileNameArray[0]);
        // list of html image elements
        //alert(fileString);

      title = document.getElementById('title');
      sketchUpObj = document.getElementById('sketchUpObj');
      imageCount = imageFileNameArray.length-1;
      //alert(imageCount);
      var bigDiv = document.getElementById("sketchUpObj");
      // load up the imageArray with the sketchUp images
      var left = sketchUpObj.offsetLeft - 8;
      var top =  sketchUpObj.offsetTop - 5;
      var path = "./images/interactiveView/" + newSku +"/";
      //alert(path + imageFileNameArray[0]);
      for (t = 0; t < imageCount; t++) 
      {
       
        if (t < imageCount)
        { //alert(path + imageFileNameArray[t]);
            sketchUpImageArray[t] = new Image();
            sketchUpImageArray[t].src = path + imageFileNameArray[t];
            //alert(path + imageFileNameArray[t]);
            sketchUpImageArray[t].className = 'sketchUpImage';
            sketchUpImageArray[t].style.left = left + "px";
            sketchUpImageArray[t].style.top = top + "px";
            hide(sketchUpImageArray[t]);
            bigDiv.appendChild(sketchUpImageArray[t]);
        }
      }
      
      //alert(path + imageFileNameArray[t]);

      // create a transparent sheet over the images so that the mouse
      // events go it it

      var sheet = document.createElement("DIV");

    //alert(sketchUpImageArray[0].src);
      bigDiv.appendChild(sheet);
     
    // bigDiv.appendChild(sheet);
      sheet.id = "sheet";
      sheet.style.left = left + "px";
      sheet.style.top = top + "px";
      sheet.onmousemove = handleRotate;
      sheet.onmousedown = handleMouseDown;
      sheet.onmouseup = handleMouseUp;
      sheet.onmouseout = handleMouseUp;
      setOpacity(sheet, 0.0);

      currentPos = imageCount-1
      //alert(imageCount);
      show(sketchUpImageArray[currentPos]);
     
      
    
};
                 
        xReq2.send(null);
}
/**
 * When the mouse goes down, start rotating the image
 *
 * @param {Event} mousedown event
 */
function handleMouseDown(e) {
  if (!e) { e = window.event; }
  getMouseXY(e);
  mouseXOrig = mouseX;
  addToPos = 0;
  mouseIsDown = true;
}

/**
 * When the mouse goes up, stop rotating the image
 *
 * @param {Event} mouseup event
 */
function handleMouseUp(e) {
  mouseIsDown = false;
  currentPos += addToPos;
}


/**
 * Divide the width of the html object by the number of images.
 * As the mouse moves over the html object, show the appropriate image
 * giving the illusion that the user is spinning the object.
 *
 * @param {Event} mousemove event
 */
function handleRotate(e) {
  if (!e) { e = window.event; }

  if (!mouseIsDown) {
    return;
  }

  getMouseXY(e);

  // STEP is how many pixels equals an image swap
  var STEP = 10; 
  var width = sketchUpObj.offsetWidth;
  var delta = mouseX - mouseXOrig;

  addToPos = Math.floor(delta/STEP);

  //handle wrap around
  var wrap = (currentPos + addToPos) % imageCount;
  var newPos = (wrap < 0) ? imageCount + wrap : Math.abs(wrap);

  //hide everyone except the image we are over
  for (var i = 0; i < imageCount; i++) {
    hide(sketchUpImageArray[i]);
  }
  //alert(newPos);
  show(sketchUpImageArray[newPos]);

  return false;
}

//updateImg.setAttribute('onload','setTimeout(\'removeUPdating()\',1000);');


/**
 * Get the mouse position from the event e
 * @param {Event} e mouse move event
 */
function getMouseXY(e) {
  if (e.pageX) {
    mouseX = e.pageX;
    mouseY = e.pageY;
  } else {
    mouseX = event.clientX + document.body.scrollLeft;
    mouseY = event.clientY + document.body.scrollTop;
  }  

  if (mouseX < 0){mouseX = 0;}
  if (mouseY < 0){mouseY = 0;} 
}

/**
 * Get the left coordinate of the element
 */
function getLeft(element) {
  var x = 0;
  while (element) {
    x += element.offsetLeft;
    element = element.offsetParent;
  }

  return x;
};


function setOpacity(element, opacity) {
  element.style.filter = "alpha(opacity=" + Math.round(opacity*100) + ")";
  element.style.opacity = opacity;
}

/**
 * Hides the HTML element.
 * @param element HTMLElement the element we hide
 */
function hide(element) {
    
  element.style.visibility = 'hidden';
}


/**
 * show the HTML element.
 * @param element HTMLElement the element we want to see.
 */
function show(element) {
    //alert(element);
  element.style.visibility = 'visible';
}

function showInteractiveDiv(newSku)
{

    hideInteractiveDiv();
   divs = document.getElementById("divShowing").value;
   document.getElementById("divShowing").value = 1;
   divs.value = 1;
   
    var wrapper = document.getElementById("wrapper");
    var intDiv = document.createElement('div');
    intDiv.name = 'interactive';
    intDiv.id = 'interactive';
    
  var xmlDoc;
        var xReq = createXMLHttpRequest();	
    	  	
        xReq.open("GET", "./ajaxPages/ajax.trackInteractiveView.asp?newSku=" + newSku);	
       
        xReq.send(null);


   
    
    var sUO = document.createElement('div');
    sUO.id = 'sketchUpObj';
    
    intDiv.appendChild(sUO);   
    
    wrapper.appendChild(intDiv);
    
        if(window.ActiveXObject)
            {
                 document.getElementById("interactive").style.backgroundColor = "#ffffff";
                 document.getElementById("interactive").style.position = "absolute";
                 document.getElementById("interactive").style.top = "144px";
                 document.getElementById("interactive").style.left = "183px";
                 document.getElementById("interactive").style.height = "349px";
                 document.getElementById("interactive").style.width = "345px";
                 
                 
            }
            else
            {
               intDiv.setAttribute("style","background-color:#ffffff; position:absolute;  top: 144px; left: 183px; height:349px; width:345px;");
            }
    init(newSku);
    
    
   
    


}


function buildOtherViewCells(imagePath,newSku,item_number,cellCount,totalCount,bookMark, interactive, roomView)
{
                        
      // if there's no header row in the table, then iteration = lastRow + 1
      //alert(bookMark + '---bookMark1');
      //alert(cellCount + '---cellCount');
     // alert(totalCount);
      
      if (cellCount == bookMark && totalCount > amountOfPics && bookMark != 0)
      {
          var tbl = document.getElementById('otherViews');
          var row = document.getElementById('otherViewsRow');
          //var lastCell = row.cells.length;
          var arrow = document.createElement('a');
          var linkText = document.createTextNode('<');
          // left cell
          //arrow.setAttribute('href','#');       //Removed so page wouldn't jump   
          //arrow.setAttribute("onclick","removeCellsFromARSImageTable();getARSImages('" + newSku + "'," + (bookMark-1) + ")");
          arrow.onclick=function()
          {
            removeCellsFromARSImageTable();  
            getARSImages(newSku,(bookMark-1));
          }
          arrow.style.cursor = 'pointer';
          // left cell
          arrow.appendChild(linkText);
          var cellLeft = row.insertCell(0);
          cellLeft.setAttribute('width','10px')
          cellLeft.appendChild(arrow);
          
          //var row = document.getElementById('otherViewsRow');
          //var lastCell = row.cells.length;
          
          //lastCell = row.insertCell(0);
          //lastCell.appendChild(arrow);
      }   
      
      var tbl = document.getElementById('otherViews');
      var row = document.getElementById('otherViewsRow');
            
      var lastCell = row.cells.length;

      var iteration = lastCell;
      var cellLeft = row.insertCell(iteration);
        cellLeft.id = "cellLeft"      

      

      var  newimg=document.createElement('img');
      var newlink=document.createElement('a');
      
      newlink.setAttribute("href",imagePath);
      newlink.setAttribute("rel","lightbox-otherview");

      newimg.src= imagePath;
      
      //alert(imagePath);
      newimg.setAttribute('width','60');
      newimg.setAttribute('height','60');
      
     //newimg.setAttribute('onclick',"swatchImageChange('" + imagePath + "','');showInteractiveDiv();");
     

     
     if (interactive == 1)
     {
     	
       newimg.onclick=function()
          {
            
            swatchImageChange(imagePath,'',newSku);
         
           // hideRoomDiv();
            showInteractiveDiv(newSku);
            
         
          }
     }
    
     else
     {
     
     newimg.onclick=function()
          {
            
            swatchImageChange(imagePath,'',newSku);
            hideInteractiveDiv();
           // hideRoomDiv();
         
          }
     }
      
      newimg.setAttribute('title',"Click to see another view of Smartfurniture product " + newSku);

  
      newlink.appendChild(newimg);
      cellLeft.appendChild(newlink);
             if(window.ActiveXObject)
            {
                 document.getElementById("cellLeft").style.width = "60px";
                 
                 
            }
            else
            {
                    cellLeft.setAttribute('width','60')
            }
         cellLeft.setAttribute('valign','top');
       
        if(interactive == 1)
           {
                 var textNode = document.createTextNode("\n");
                 var intPic = document.createElement('img');
                 intPic.src = './images/viewBlock.gif';
                 intPic.setAttribute('width','60');
                 intPic.setAttribute("onclick","showInteractiveDiv('" + newSku + "');");
                 cellLeft.setAttribute('align','center');
                 
              
                 cellLeft.appendChild(textNode);
                 cellLeft.appendChild(intPic);
           }
         if(roomView == 1)
           {
                 var textNode = document.createTextNode("\n");
                 var intPic = document.createElement('img');
                 intPic.src = './images/room.gif';
                 intPic.setAttribute('width','60');
                 intPic.setAttribute('onclick','showRoomDiv();');
                 cellLeft.setAttribute('align','center');
                 
              
                 cellLeft.appendChild(textNode);
                 cellLeft.appendChild(intPic);
           }
          
      var row = document.getElementById('otherViewsRow');
      var lastCell = row.cells.length;
      // if there's no header row in the table, then iteration = lastRow + 1
      //alert(lastCell);
      
      

      var iteration = lastCell;
      if (bookMark != 0)
      {
      if (totalCount > amountOfPics && lastCell > amountOfPics && bookMark < totalCount-amountOfPics) //|| bookMark == 0 && totalCount > 5 && lastCell > 3)
      {
        //alert(cellCount-bookMark + '---bookMark');
          var tbl = document.getElementById('otherViews');
          var row = document.getElementById('otherViewsRow');
          var lastCell = row.cells.length;
          var arrow = document.createElement('a');
          linkText = document.createTextNode('>');
          //arrow.setAttribute('href','#');   //this was removed so the page wouldn't jump when clicked on jb
          arrow.onclick=function()
          {
            removeCellsFromARSImageTable();  
            getARSImages(newSku,(bookMark+1));
          }
          arrow.style.cursor = 'pointer';
          //arrow.setAttribute("onclick","removeCellsFromARSImageTable();getARSImages('" + newSku + "'," + (bookMark+1) + ")");
          // left cell
          arrow.appendChild(linkText);
          var cellLeft = row.insertCell(lastCell);
          cellLeft.setAttribute('width','10px')
          cellLeft.appendChild(arrow);

      }
      }
      else
      {
      if (totalCount > amountOfPics && lastCell > (amountOfPics-1) && bookMark < totalCount-amountOfPics) //|| bookMark == 0 && totalCount > 5 && lastCell > 3)
      {
        //alert(cellCount-bookMark + '---bookMark');
          var tbl = document.getElementById('otherViews');
          var row = document.getElementById('otherViewsRow');
          var lastCell = row.cells.length;
          var arrow = document.createElement('a');
          arrow.id = 'rightArrow1';
          linkText = document.createTextNode('>');
          //arrow.setAttribute('href',"#");
          arrow.onclick=function()
          {
            removeCellsFromARSImageTable();  
            getARSImages(newSku,(bookMark+1));
          }
          arrow.style.cursor = 'pointer';
          //arrow.setAttribute('style','cursor:hand;');
          //arrow.onclick = alert('test');
          //arrow.mouseClick = removeCellsFromARSImageTable();getARSImages(newSku,(bookMark+1));
          //arrow.setAttribute("mouseClick","removeCellsFromARSImageTable();getARSImages('" + newSku + "'," + (bookMark+1) + ")");
          
          // left cell
          arrow.appendChild(linkText);
          
          var cellLeft = row.insertCell(lastCell);
          cellLeft.setAttribute('width','10px')
          cellLeft.appendChild(arrow);
          //document.getElementById('rightArrow1').style.cursor = 'pointer';
      }
      }   
   
}

function createXMLHttpRequest() {
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new XMLHttpRequest(); } catch(e) {}
   alert("XMLHttpRequest not supported");
   return null;
}

function importXML(sXML)
{
	var xmlDoc;
	var output;
	
	if (document.implementation && document.implementation.createDocument)
	{
	    //alert('Test');
	    //alert(sXML);
		xmlDoc = document.implementation.createDocument("", "", null);
        xmlDoc.async="false";
        xmlDoc = new DOMParser().parseFromString(sXML, 'text/xml');
     
	}
	else if (window.ActiveXObject)
	{
	    //alert('test2');
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(sXML);
 	}
	else
	{
		alert('Your browser can\'t handle this XML script');
		return;
	}
	
	
	return xmlDoc;
}

function removeCellsFromARSImageTable(table,row)
{

  var tbl = document.getElementById('otherViews');
  var row = document.getElementById('otherViewsRow');
  var lastCell = row.cells.length;

  for(var s = 0; s < lastCell; s++)
  { 
    row.deleteCell(0);
  }
}