/*

 A link to this script is inserted by PHP when needed.

 Some arrays are passed by PHP and converted to JAVASCRIPT associative,
          which is not the same as PHP associative but still useful  ..

 The other way is to create javascript objects which may have been better.

*/

var orderedCategories = js_categories;
// Get products / category - make associative.
var numCats = js_categories.length;
var lastCat = js_categories[numCats];
var numItemsThisCategory = new Array(numCats);
var firstProdThisCategory = new Array(numCats);
var categorieNames = new Array(numCats);

var thumbs = new Array(numCats);
var ajaxNum = new Array(numCats);
var position = new Array(numCats);

var backRefs = new Array(numCats);

for (var $ii = 0; $ii < numCats; $ii++) {
  var categories_PHP = js_categories[$ii];
  var lastCat = js_categories[$ii];
  //
  var productsThisCat = js_productsThisCategory[$ii];
  //
  thumbs[categories_PHP] = new Array(productsThisCat);
  numItemsThisCategory[categories_PHP] = productsThisCat;
  firstProdThisCategory[categories_PHP] = js_firstProdThisCategory[$ii];
  categorieNames[categories_PHP] = js_catNames[$ii];
  backRefs[categories_PHP] = new Array(productsThisCat+1);
  ajaxNum[categories_PHP] = 0;
}

delete js_productsThisCategory;
//delete js_firstProdThisCategory;
delete js_catNames;
delete js_categories;

var scrollInterval;
var thumbsfolderUrl;

// Refrences the downloadeded images.
var imgNameIdArray = new Array(numFilesToget);

function refsObj () {
  // When an image is moved to it's reserved slot, it's parameters also have to be associated with tht slot.
  // price, product code, url etc.
  // Was not possible for ME to extend the img object to accomodate this, or at least I could but it
  // would not work with OPERA.
  //
  this.setRefs = setRefs;
  //The circle within the circle.
}

function setRefs (text, prodNum, stock_level, width) {
  this.text = text;
  this.prodNum = prodNum;
  this.stock_level = stock_level;
  this.width = width;
}


function b (imageNum, prodNum, catId, text, thumbName, width, nextProdNum, stock_level) {
  this.tempImgObject = false;
  this.imageNum = imageNum;
  this.prodNum = prodNum;
  this.catId = catId;
  this.thumbName = thumbName;
  this.width = parseInt(width);
  this.left = 0;
  this.text = text;
  this.nextProdNum = nextProdNum;
  this.stock_level = stock_level;
  this.saveImgObj = false;
  this.fireLoad = false;
  this.saveImgObj.complete = false;
  loadSource2(this);
}

function loadSource2(obj) {
  obj.saveImgObj = new Image(obj.width, thumbHeightsfromPHP);
  obj.saveImgObj.onload = function () {
    obj.fireLoad = true;
    ajaxNextThumb (obj.catId);
  }
  obj.saveImgObj.src = thumbsfolderUrlfromPHP + obj.thumbName;
}

function setPosition (cat_id) {
  this.cat_id = cat_id;
  this.gap = thumb_spacer;
  this.scrolling = false;
  this.allLoaded = false;
  this.nextImageLeft = 2;
  this.nextImageNum = 0;
  this.image_x = 0;
  this.nextImgSlot = 0;
  this.firstVisibleSlotNumber = 0;
  this.firstVisibleSlot = "i_" + this.cat_id + "_" + 0;
  this.adjust = adjust;
  this.setNextImg = setNextImg;
  this.current_slot = reserveDivs + 1;
  this.getNextSlot = getNextSlot;
}

function gt () {
  this.frameLapse = frameLapse;
  this.scrollLeft = 0;
  this.mSecs = mSecs;
  this.resetScroll = resetScroll;
  this.n_millisecs = this.o_millisecs = this.mSecs (new Date());
}

function frameLapse () {
  this.n_millisecs = this.mSecs (new Date()) - this.o_millisecs;
  this.scrollLeft = Math.ceil(targetFramesPerMilliSecond * this.n_millisecs * -1);
  return this.scrollLeft;
}

function mSecs (d) {
  return ((60*(60*(d.getHours()+(24*d.getDay()))+d.getMinutes()) + d.getSeconds())*1000) + d.getMilliseconds();
}

function gt2() {
  this.frameLapse = frameLapse;
  this.scrollLeft = 0;
}

function frameLapse2() {
  this.scrollLeft -= targetFramesPerMilliSecond;
  return this.scrollLeft;
}

function resetScroll () {
  // After suspending .. timer will be out.
  this.o_millisecs += (this.mSecs (new Date()) - this.o_millisecs) - this.n_millisecs;
}

function removePX (withPX) {
  var strLen = withPX.length-2;
  return parseInt(withPX.substr(0, strLen));
}

function adjust (lastCat) {

  // All to be prepared for scrolling before beginning to scroll.
  if (!this.scrolling) this.setNextImg ();

  if (!allScrolling) return 0;

  // Probable large AJAX delay - Something is overloaded - image is not yet available .. best to wait .. avoid additional queue. Need to check both object and onload condition .. Also cannot refer to object property unless object exists ... Assumption is that 99 times out of 100 it will exist.
  if (!((thumbs[this.cat_id][this.nextImageNum])&&(thumbs[this.cat_id][this.nextImageNum].fireLoad)))
    return 0;

  // Smooth out display a little - move container only once for each set of categories, use timelapse vs. pixellapse.
  if (lastCat && moveAmount) {
    // When PC is overloaded saves cycles.
    var z0 = moveAmount.scrollLeft;
    var z = moveAmount.frameLapse ();
    if (z0 == z) return 0;
    container_div.style.left = z + "px";
  }

  var objRef = document.getElementById(this.firstVisibleSlot).style;
  var objLeft = moveAmount.scrollLeft + removePX (objRef.left) + removePX (objRef.width);

  // Relocate unused divs ..
  if ((objLeft) < 2) {
    objRef.display = "none";
    this.firstVisibleSlotNumber = nextPos(this.firstVisibleSlotNumber, reserveDivs);
    this.firstVisibleSlot = "i_" + this.cat_id + "_" + this.firstVisibleSlotNumber;
    //
    this.setNextImg ();
    //
  }
  return 0;

}

function setNextImg () {
  // Add an image to the (far) right end of the active list of images & prepare for next pass.
  var refThumb = thumbs[this.cat_id][this.nextImageNum];
  var nextImg = refThumb.saveImgObj;

  var nextSlotObj = document.getElementById(this.getNextSlot());

  // Required to dereference on mouseover, because cannot extend image class.
  backRefs[this.cat_id][this.current_slot].setRefs(refThumb.text, refThumb.prodNum, refThumb.stock_level, nextImg.width);

  with (nextSlotObj) {
    src = nextImg.src;
    style.width = nextImg.width + "px";
    style.left = this.nextImageLeft + "px";
    style.display = "inline";
    thumbNum = refThumb.imageNum;
    cat_id = refThumb.cat_id;
  }

  this.nextImageLeft += refThumb.width + this.gap +(css_borders*2);
  this.nextImageNum = nextPos(this.nextImageNum, (numItemsThisCategory[this.cat_id]));
}

function getNextSlot () {
  this.current_slot = ((reserveDivs-1) > this.current_slot)? this.current_slot += 1: 0;
  return "i_" + this.cat_id + "_" + this.current_slot;
}

function nextPos(ii, maxItems) {
  if (ii<(maxItems-1)) {
    return ii+1;
  } else {
    return 0;
  }
}
var container_div;

function canStart() {

  // The scrolling object.
  container_div = document.getElementById("b-99");
  for (var cat_id in categorieNames) {
    // Positioning Objects.
    position[cat_id] = new setPosition(cat_id);
    // Start sequence.
    getName(cat_id, 0, firstProdThisCategory[cat_id]);
  }
}

var allScrolling = false;

function ajaxNextThumb (cat_id) {

  var imageNum = ajaxNum[cat_id];

  var thumbObj = thumbs[cat_id][imageNum];

  thumbObj.saveImgObj.thumbNum = imageNum;
  thumbObj.saveImgObj.cat_id = cat_id;
  var catObj = position[cat_id];

  catObj.allLoaded = ((imageNum) < (numItemsThisCategory[cat_id]-1))? false: true;

  //var catObj = position[cat_id];

  if (!catObj.scrolling) {
    if (allScrolling) alert("err 1");
    // Line up images - no scrolling yet.
    catObj.adjust(false);

    // Obtain enough images to fill the screen - or none left in category.
    var enoughImagesForNow = (position[cat_id].nextImageLeft < (reservedSlotsWidth/1.75))? false: true;

    if (enoughImagesForNow || catObj.allLoaded) {
      catObj.scrolling = true;

      // Must not start scroll until static positioning for all categories is complete.
      for (cateGory in categorieNames) {
        if (position[cateGory].scrolling) {
          allScrolling = true;
          continue;
        }
        allScrolling = false;
        break;
      } // efor.

    }

    if (allScrolling) {
      if (!scrollDisable) {
        setTimeout (startScroll, waitBeforScroll);
      }
    }
  }

  // Does not set new imageNum until object is loaded.
  if (!(catObj.allLoaded)) {
    // Previous item is complete - Get BIOS for the next one from server.
    ajaxNum[cat_id]++;
    getName(cat_id, ajaxNum[cat_id], thumbs[cat_id][ajaxNum[cat_id]-1].nextProdNum);
  }
}

// Function doAdjusts is sent from php.
function makeHttpRequest(url, callback_function, async) {
  var http_request = false;

  if (window.XMLHttpRequest) {
    // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    // If not XML do the following .. If method exists .. else Firefox error ..!
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/html');
    }
  } else if (window.ActiveXObject) {
    // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
      }
    }
  }

  if (!http_request) {
    alert('Unfortunately you browser doesn\'t support this feature.');
    return false;
  }

  http_request.onreadystatechange = function() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        // alert(http_request.responseText);
        eval(callback_function + http_request.responseText+')');
      } else {
        window.status = "Lost contact with server, Please refesh the page and check your internet connection !";
        //alert('There was a problem with the request.(Code: ' + http_request.status + ')');
      }
    }
  }

  http_request.open('POST', url, async);
  http_request.send(null);
}

function getName(catid, imageNum, nextProdId) {
  var f0 = "thumbs["+catid+"]["+imageNum+"] = new b("+imageNum+",";
  makeHttpRequest(".\/various-mods\/banner_1_newLook\/AjaxResponse.php?PHPSESSID="+mySession+"&catRequest="+catid+"&inputText="+nextProdId, f0, true);
}

var scrollDisable = false;
var scrollingBeforeStopped = true;
function stop (objRef) {
  scrollDisable = true;
  scrollingBeforeStopped = allScrolling;
  if (allScrolling) window.clearInterval(scrollInterval);
}
moveAmount = false;
function go () {

  showText(false);

  scrollDisable = false;

  if (!allScrolling) return 0;
  window.clearInterval(scrollInterval);
  if (moveAmount) moveAmount.resetScroll();
  scrollInterval = setInterval("doAdjusts ()", scrollSpeed);
}

function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function goToURL (refObjRef) {
  refProperties = deRefId (refObjRef.id);
  window.open(prodPathUrlfromPHP + refProperties.prodNum, "_self");
}

function goToCatURL (catNum) {
  window.open(catPathUrlfromPHP + catNum, "_self");
}

function showText(show, refObjRef) {

  var ref = document.getElementById("hcBannerText");

  if (!show) {
    ref.style.display = "none";
    return 0;
  }

  // Don't ask !!
  if (!refObjRef) return 0;

  var refProperties = deRefId (refObjRef.id);

  var str = refObjRef.style.top;
  strLen = str.length-2;
  var objTop = parseInt(str.substr(0, strLen));
  var str = refObjRef.style.left;
  strLen = str.length-2;

  var offSet = (!moveAmount)? 0: moveAmount.scrollLeft;
  var objLeft = parseInt(str.substr(0, strLen)) + offSet;

  var inStock = (refProperties.stock_level > 0)? "In Stock " + Math.min(50, refProperties.stock_level): "<span style=\"color:#ff0000\">Out of Stock</span>";

  var stockCount = "/" + inStock;
  var text = refProperties.text+ "<span class='codedesc'>&nbsp;(Code " +refProperties.prodNum + stockCount +")</span>"


  with (ref) {
    style.top = objTop + 3 + "px";
    style.display = "block";
  }

  if ((objLeft) < (bannerWidth/2)) {
    with (ref)
    {
      innerHTML  = "&larr;&nbsp;" + text;
      style.left = (objLeft + refProperties.width - 3) + "px";
    }

  } else {
    with (ref) {
      innerHTML = "&nbsp;" + text + "&rarr;";
      style.left = (objLeft - ref.offsetWidth + 3) + "px";
    }

  }




}

function deRefId (imgIdRef) {
  var bits = imgIdRef.split("_");
  return backRefs[bits[1]][bits[2]];
}
