// global variables
var compareWidth; //previous width used for comparison
var detector; //the element used to compare changes
// for performance, I store the detector element into a variable to avoid
// running a DOM query every time we need to test the change conditions




jQuery(document).ready(function(){
    //set the initial values
    detector = jQuery('#main');
    compareWidth = 0;

    function resizeScreen(){
          //compare everytime the window resize event fires
        if(detector.width()!=compareWidth){

            //a change has occurred so update the comparison variable
            compareWidth = detector.width();
            if(compareWidth ==950){
              console.log('big');
              jQuery('#container').after(jQuery('#primary'));  
              makeNormalView();             
            }else if (compareWidth==296){
              console.log('small');
              jQuery('#container').before(jQuery('#primary'));  
              makeMobileView();          
             
            }else if (compareWidth==480){
              console.log('medium');
              jQuery('#container').before(jQuery('#primary'));  
              makeWideMobileView();          
             
            }
            // add the code you want to run here
            // you can pass the new sizes to functions if required
            // e.g. myfunction(detector.width(),detector.height());

        }
    }
    function clearEvents(){
      jQuery('#primary .widgetcontainer h3').unbind('click').removeClass('open');    
    }
    
    function makeNormalView(){
          clearEvents();
      jQuery('#primary .widgetcontainer :nth-child(2)').show();

    
    
    }
    function makeMobileView(){
          clearEvents();
      jQuery('#primary .widgetcontainer').each(function(){
        var $widget = jQuery(this)
        jQuery('h3',$widget).click(function(){
          jQuery(':nth-child(2)',$widget).slideToggle(200, function(){
            if(jQuery(this).is(":visible")){
              jQuery('h3',$widget).addClass('open');
              
            }else{
              jQuery('h3',$widget).removeClass('open');
            }
          
          });
        });
        
        jQuery(':nth-child(2)',$widget).hide();
      })
    }
    
    function makeWideMobileView(){
          clearEvents();
      jQuery('#primary .widgetcontainer').each(function(){
        var $widget = jQuery(this)
        jQuery('h3',$widget).click(function(){
          jQuery(':nth-child(2)',$widget).slideToggle(200, function(){
            if(jQuery(this).is(":visible")){
              jQuery('h3',$widget).addClass('open');
              
            }else{
              jQuery('h3',$widget).removeClass('open');
            }
          
          });
        });
        
        jQuery(':nth-child(2)',$widget).hide();
      })
    }    
    
    jQuery(window).resize(function(){
      resizeScreen();

    });
    resizeScreen();

});
