/******************************************************
 * Handle the click on the updates element to add a
 * slide effect to the custom ENowIt Widget
 * @Author Scott Benes (sbenes)
 * @Requires jquery.js
 ******************************************************/

(function($){
    
  window.initForm = function(){
    
    $('#catalog_form label.address_line_first').text('Address');
    
    var popup = $('#catalog_form');
    if(popup.length > 0) {
      if(popup.is(':visible')){
        popup.show().stop().css({height: popup.find('.miwt').height() });
      }
    }   
  };
  
})(jQuery);

(function(){
  // function to call everytime the miwt dom is updated
  var onDomUpdate = function(){
    initForm();
  };
  // register a function to call everytime miwt is updated
  var miwtLoaded = function(){
    miwtajax.addMIWTAJAXRequestCompleteCallback(onDomUpdate);
  };
  // Poll for presence of miwtajax
  var ct = 0;
  window.setTimeout(function pollForMIWT(){
    if (typeof miwtajax !== 'undefined') {
      miwtLoaded();
    } else if (ct++ < 50) {
      window.setTimeout(pollForMIWT, 100);
    }
  }, 100);
})();



var bWidgetInit = false;

jQuery(function($){
  
  //run the MIWT update method on page load
  initForm();
  
  $('#updates').click(function(){
    
    //check if widget is already initialized, handles the case that it is already visible and the click is meant to close
    if(!bWidgetInit){
      displayWidget(1283); // real code 1283 demo is 238
      bWidgetInit = true;
    }
    
    var widget = $(this).parent().find('#widgetBox');
    //check if widget is already being animated, dont do anything if it is
    if(widget.is(':animated')){
      return;  
    }
    
    //cannot do normal .is(':visible') check because of the widgets css control
    if(widget.height() > 1){
      widget.animate({'height' : '1px'}, function() {
        $(this).toggleClass('widgetActive');
        bWidgetInit = false;
      });
    } else {
      widget.toggleClass('widgetActive').animate({'height' : '350px'});
    }
  });
  
  $('#icontact h2').click(function(){
    var popup = $(this).closest('#icontact').find('.icontact_popup');
    if(popup.length > 0) {
      if(popup.is(':visible')){
        popup.stop().animate({height: 0}, function(){ popup.hide(); });
      } else {
        popup.show().stop().animate({height: 260});
      }
    }
    
  });
  
  $('#catalog_heading h2').click(function(){
    var popup = $('#catalog_form');
    if(popup.length > 0) {
      if(popup.is(':visible')){
        popup.stop().animate({height: 0}, function(){ popup.hide(); });
      } else {
        popup.show().stop().animate({height: popup.find('.miwt').height()});
      }
    }
    
  });  
});
