// global state variables
window.sizeSelected = null;

window.step1 = false;

window.onload = function() {
   // sizeOpt events
   var aSize = $('sizeOpt').getElementsByClassName('size');
   for( i=0; i < aSize.length; i++ ) {
      $(aSize[i]).addEvent('mouseover', sizeMouseover);
      $(aSize[i]).addEvent('mouseout', sizeMouseout);
      $(aSize[i]).addEvent('click', sizeClick);
   }

   // cart submit event
   $('cartadd').addEvent('submit', cartSubmit);
   
   updateState();   
};

// event handler functions
function sizeMouseover( e ) {
   if( this.style.borderColor != '#0000ff' && this.style.borderTopColor != 'blue' ) {
      this.style.borderColor = 'black';
   }
}
function sizeMouseout( e ) {
   if( this.style.borderColor != '#0000ff' && this.style.borderTopColor != 'blue' ) {
      this.style.borderColor = 'white';
   }
}
function sizeClick( e ) {
   var colors = $('sizeOpt');
   for (var i = 0; i < colors.childNodes.length; i++) {
      if( colors.childNodes[i].nodeName == 'DIV' ) {
         colors.childNodes[i].style.borderColor = 'white';
      }
   }
   window.sizeSelected = this.id;
   this.style.borderColor = 'blue';
   $('sizeError').style.display = 'none';
   $('sizeFill').value = this.id;
   for( i = 0; i < this.childNodes.length; i++ ) {
      if( this.childNodes[i].nodeName == 'DIV' ) {
         $('cartadd').size.value = this.childNodes[i].id;
         break;
      }
   }
   for( i = 0; i < this.childNodes.length; i++ ) {
      if( this.childNodes[i].nodeName == 'SPAN' && this.childNodes[i].className == 'sale' ) {
         $('priceFill').value = this.childNodes[i].innerHTML;
         break;
      }
   }
   window.step1 = true;
   
   updateState();
}
function cartSubmit( e ) {
   if( window.step1 == false ) {
      // select size error
      $('sizeError').style.display = 'block';
      DOMAss.preventDefault(e);
   } else {
      $('cartadd').submit();
   }
}

function updateState() {
   if( window.step1 == true ) {
      // grey step1
      $('step1').src = 'img/step1-grey.jpg';
      // set step2
      $('step2').src = 'img/step2.jpg';
      //enable addButton
      $('addToCart').src = 'img/add-green.png';
   } else { $('step1').src = 'img/step1.jpg'; }
}

function soloSize() {
   window.step1 = true;
   updateState();
}
