/**************************************************************
   AUTHOR:  Pat Heard (fullahead.org)
   DATE:    2009.06.24
   PURPOSE: Utility functions and event definitions
 **************************************************************/

// Adds the 'js' class to the body tag.  This allows us to hide all css meant for people without Javascript
document.documentElement.className = 'js';

/*
 * Constants script values
 */
var Constants = {
    
   // Cluster constants and index into CLUSTER_DOM_REF below

   CLUSTER_UPLOAD : 0,
   CLUSTER_ORGANIZE : 1,
   CLUSTER_SHARE : 2,
   CLUSTER_REPORT : 3, 
   CLUSTER_HOME : 4,
   CLUSTER_HOME_COUNT : 5,   
   
   // IDs of each cluster's tagline and class names of each cluster's link
   CLUSTER_DOM_REF : [
      'upload', 
      'organize', 
      'share', 
      'report',
      'home'
   ],

   // Array index of 2 dimensional cluster image arrays below
   PATH : 0,
   ID : 1,
   TOP : 2,

   homeCluster01 : [
      ['img/cluster/home/01/vintage-car.jpg', 'car', 263], 
      ['img/cluster/home/01/woman.jpg', 'woman', 217],
      ['img/cluster/home/01/football.jpg', 'football', 226], 
      ['img/cluster/home/01/robot.jpg', 'robot', 90], 
      ['img/cluster/home/01/autobahn.jpg', 'autobahn', 23]
   ],
   
   homeCluster02 : [
      ['img/cluster/home/02/galaxy.jpg', 'galaxy', 218], 
      ['img/cluster/home/02/robot.jpg', 'robot-head', 150],
      ['img/cluster/home/02/lightening.jpg', 'lightening', 180], 
      ['img/cluster/home/02/gear.jpg', 'gear', 15]
   ],
   
   homeCluster03 : [
      ['img/cluster/home/03/runner.jpg', 'runner', 220], 
      ['img/cluster/home/03/engine.jpg', 'engine', 220],
      ['img/cluster/home/03/car.jpg', 'hillbilly', 107], 
      ['img/cluster/home/03/tree.jpg', 'trees', 21], 
      ['img/cluster/home/03/northern-lights.jpg', 'nothern-lights', 44]
   ],
   
   homeCluster04 : [
      ['img/cluster/home/04/soccer.jpg', 'soccer', 200], 
      ['img/cluster/home/04/controls.jpg', 'control-panel', 125],
      ['img/cluster/home/04/kid.jpg', 'super-kid', 61], 
      ['img/cluster/home/04/bumper-car.jpg', 'bumper-car', 181], 
      ['img/cluster/home/04/planet.jpg', 'planet', 18]
   ],
   
   homeCluster05 : [
      ['img/cluster/home/05/electricity.jpg', 'electricity', 235], 
      ['img/cluster/home/05/kid.jpg', 'kid-foot', 126],
      ['img/cluster/home/05/tree.jpg', 'tree-hugger', 41], 
      ['img/cluster/home/05/leaves.jpg', 'leaves', 94], 
      ['img/cluster/home/05/wind.jpg', 'wind', 17]
   ],   

   uploadClusterImages : [
      ['img/cluster/upload/text-custom.gif', 'uploadCustomTxt', 17],
      ['img/cluster/upload/text-browser.gif', 'uploadBrowserTxt', 40],      
      ['img/cluster/upload/upload.gif', 'uploadImg', 80]
   ],   
   
   organizeClusterImages : [
      ['img/cluster/organize/text-unlimited.gif', 'organizeUnlimitedTxt', 13],
      ['img/cluster/organize/organize.gif', 'organizeImg', 65]
   ],
   
   shareClusterImages : [
      ['img/cluster/share/homestead.jpg', 'homestead', 263],
      ['img/cluster/share/plank.jpg', 'plank', 204],
      ['img/cluster/share/filmcore.jpg', 'filmcore', 186],
      ['img/cluster/share/bug.jpg', 'bug', 107],
      ['img/cluster/share/text.gif', 'shareTxt', 16]
   ],   
   
   reportClusterImages : [
      ['img/cluster/report/text.gif', 'reportTxt', 14],
      ['img/cluster/report/graph-fg.gif', 'reportFgImg', 121],
      ['img/cluster/report/graph-bg.gif', 'reportBgImg', 131]
   ],   
   
   
   // Array that contains all the above image cluster arrays.  Allows for simplified switching between clusters.
   clusters : null,
   
   init : function(){
  
      // This must be initialized after the image cluster arrays have been created
      Constants.clusters = [
         Constants.uploadClusterImages, 
         Constants.organizeClusterImages, 
         Constants.shareClusterImages, 
         Constants.reportClusterImages,
         Constants.homeCluster01,
	 Constants.homeCluster02,
	 Constants.homeCluster03,
	 Constants.homeCluster04,
         Constants.homeCluster05
      ];
   }
}



/*
 * Common utilities
 */
var Utils = {

   // Takes a multi dimensional array and returns the specified item at each index as a single dimensional array   
   arrayMultiToSingle : function(item, a){
      var paths = new Array();
      for(var i = 0; i < a.length; i++)
         paths.push(a[i][item]);
      return paths;
   }  
}


/*
 * Showing and hiding the 
 */
var Actions = {

   currentCluster : null,    // Currently displayed image cluster
   loader : null,            // Reference to animated loading gif
   ready : true,             // Is the cluster ready for a transition?
   activatedLink : null,     // The link that should have the black bg applied once the transition starts


   // Create the home page image cluster
   init : function(){

      // Hide the noscript image cluster and stop it from loading
      var cluster = $('cluster');
      if(cluster)
         cluster.destroy();
   
      // Attach the click events to all lins that can change the cluster images
      Actions.attachClickEvent($$('li.upload a', 'a.upload'), Constants.CLUSTER_UPLOAD);
      Actions.attachClickEvent($$('li.organize a', 'a.organize'), Constants.CLUSTER_ORGANIZE);
      Actions.attachClickEvent($$('li.share a', 'a.share'), Constants.CLUSTER_SHARE);
      Actions.attachClickEvent($$('li.report a', 'a.report'), Constants.CLUSTER_REPORT);
      
      // Capture a reference to the loader gif
      Actions.loader = $('loader');
      
      // Show a random home image cluster
      var idx = Constants.clusters.length - 1 - Math.floor(Constants.CLUSTER_HOME_COUNT * Math.random());
      Actions.show(idx);
   },
   
   
   
   
   // Displays the requested image cluster
   show : function(clusterToShow, link){
     
      // Only try to display a cluster if it isn't currently in view
      if(Actions.currentCluster != clusterToShow && Actions.ready) {

         // Hide the currently displayed section and bring the requested section into view
         Actions.ready = false;
         Actions.hide();
         Actions.activateLink(clusterToShow);   
         Actions.showCluster(clusterToShow);           
        
      }
      return false;
   },
   
   
   
   
   // Hides the currently displayed image cluster
   hide : function(clusterToHide){
   
      // Only try to hide if it isn't null
      if(Actions.currentCluster != null) {
         Actions.hideCluster(Actions.currentCluster);
  
         // Fade the loading gif in after a 0.5 second delay
         if(Actions.loader) 
            (function(){Actions.loader.morph({'opacity': 1})}).delay(250);   
      }
   },
   
   
   
   
   // Displays the Home image cluster
   showCluster : function(clusterToShow){
   
      // Preload the individual images that will make up the image cluster
      var clusterImgs = new Asset.images(Utils.arrayMultiToSingle(Constants.PATH, Constants.clusters[clusterToShow]), {
         onComplete: function(){
      
            // Fade the loading gif out after a 0.5 second delay
            if(Actions.loader) 
               (function(){Actions.loader.morph({'opacity': 0})}).delay(250);      
      
            // Displays the Home tagline text
            Actions.displayTagline(clusterToShow);
            
            // Create the <img>'s that make up the cluster and bring them into view after a 1 second delay
            var actions = $('actions');
            if(actions) {
               (function(){
                  for(var i = 0; i < Constants.clusters[clusterToShow].length; i++){
                     var img = new Element('img', {
                        'id': Constants.clusters[clusterToShow][i][Constants.ID],
                        'src': Constants.clusters[clusterToShow][i][Constants.PATH]
                     });
                     
                     // Clicking the image cluster will now cycle to the next cluster
                     img.addEvent('click', function(){
                       Actions.show(clusterToShow >= 3 ? 0 : clusterToShow + 1);
                     });
                     
                     img.inject(actions);  
                     img.set('morph', {duration: 1000});
                     img.morph({'top': Constants.clusters[clusterToShow][i][Constants.TOP]});               
                  }
                  
                  // Apply the black background as the transition is running
                  if(Actions.activatedLink){
                     Actions.activatedLink.set('morph', {duration : 1000});
                     Actions.activatedLink.morph({'background-position': [-400, 0], 'color': '#fff'});
                  }   
                  
                  Actions.currentCluster = clusterToShow;
                  Actions.ready = true;
               }).delay(1000);
            }
         }
      });
   }, 
   
   
   
   
   // Hides the Home image cluster
   hideCluster : function(clusterToHide){
      for(var i = Constants.clusters[clusterToHide].length - 1; i > -1; i--){
         var img = $(Constants.clusters[clusterToHide][i][Constants.ID]);
         if(img){
            img.set('morph', {duration: 1000, onComplete : function(img){img.destroy();}}); 
            img.morph({'top': 380}); 
         }
      } 
   },   
   
   
   
   
   
   // Displays the tagline text of the new section
   displayTagline : function(clusterToDisplay){
   
      if(Actions.currentCluster != null){
      
         var toHide = $(Constants.CLUSTER_DOM_REF[Actions.currentCluster]);
         toHide = toHide == null ? $('home') : toHide;
         toHide.set('opacity', 1);            
         toHide.set('morph', {duration: 1000, onComplete : function(toHide){
            toHide.removeClass('active');
            var toShow = $(Constants.CLUSTER_DOM_REF[clusterToDisplay]);
            toShow.set('opacity', 0);
            toShow.addClass('active');              
            toShow.set('morph', {duration: 1000});
            toShow.morph({'opacity': 1});
         }});
         toHide.morph({'opacity': 0});     
         
      }   
   },
   
   // Shows a clicked link as active with the black background
   activateLink : function(clusterToShow){
      
      // deactivate the currently displayed link
      Actions.deactivateLink();
      
      if(clusterToShow != Constants.CLUSTER_HOME){      
         var link = $$('li.' + Constants.CLUSTER_DOM_REF[clusterToShow] + ' a');
         if(link){
            link.addClass('active');
            link.morph({'background-position': 0});
            Actions.activatedLink = link.getFirst('strong'); 
         }      
      }
   },
   
   // Shows a clicked link as inactive (removes black background)
   deactivateLink : function(){      
      if(Actions.currentCluster != null && Actions.currentCluster < Constants.CLUSTER_HOME){ 
         var link = $$('li.' + Constants.CLUSTER_DOM_REF[Actions.currentCluster] + ' a'); 
         if(link){
            link.removeClass('active');  
            link.morph({'background-position': -300});
            link.getFirst('strong').morph({'background-position': -400, 'color': '#111'});
                       
         }
      }
   }, 
   
   // Attach the click events to cluster links
   attachClickEvent : function(elems, clusterToShow){      
 
      for(var i = 0; i < elems.length; i++){
         elems[i].addEvent('click', function(){   
            return Actions.show(clusterToShow);
         });
      }   
   }
}



/* 
 * Login form behaviour
 */
var Login = {

   theForm : null,
   fields : null,
   popup : null,
   formType : 'client',
   clientFields : ['Job ID', 'Password', 'Your Name'],
   // adminFields :  ['Company ID', 'Password', 'User Name (leave blank if unsure)'],


   // Shows the login form
   show : function(){
      Login.theForm.morph({'opacity': 1});   
   },
   
   
   // Hides the login form
   hide : function(){
      Login.theForm.set('morph', {onComplete : function(){
        for(var i = 0; i < Login.fields.length; i++) {
           if(Login.fields[i].id == 'password') {
              try { fields[i].setProperty('type', 'text'); } catch(ex){}
           }   
           Login.fields[i].value = Login.fields[i].title;
        }   
      }});
      Login.hideErrors();
      Login.theForm.morph({'opacity': 0}); 
   },


   // Gets the login form ready
   init : function(){
   
      this.theForm = $('login');
      var loginLink = $('loginLink');
      if(this.theForm && loginLink){        
         
         // Initially hide the form
         this.theForm.set('styles', {
            'opacity': 0,
            'display': 'block'
         });
         
         // Focus/blur events for the fields
         Login.fields = $$('form#login input[type=text]');
         for(var i = 0; i < Login.fields.length; i++){
            Login.fields[i].addEvent('focus', function(){                  
               if(this.id == 'pass') {
                  try { this.setProperty('type', 'password'); } catch(ex){}
               } if(this.value == this.title)
                  this.value = '';
            });
            Login.fields[i].addEvent('blur', function(){
               if(this.id == 'pass' && this.value == '') {
                  try { this.setProperty('type', 'text'); } catch(ex){}
               } if(this.value == '')
                  this.value = this.title;
          
            });                       
         }         
         
         // Show the form
         loginLink.addEvent('click', function(){
            Login.show();   
            return false;
         });
         
         // Hide the form and reset
         $$('#login a.close').addEvent('click', function(){
            Login.hide();                                    
            return false;
         });
         
         
         // Create the popup on login button click (this is to get around popup blockers)
         // $('loginButton').addEvent('click', function(){
         //    if(Login.isClient())
         //       Login.popup = window.open("", "new", "toolbar=no,status=no,titlebar=no,menubar=no,width=900,height=700,top=0,left=0");         
         // });
         
         
         // Change login form type
         // var links = $$('form#login h2 a');
         // for(var i = 0; i < links.length; i++){
         //    links[i].addEvent('click', function(){
         //       if(!this.hasClass('active')){
         //          
         //          // Set active link to inactive
         //          var otherLink = $$('form#login h2 a.active')
         //          otherLink.removeClass('active');
         //          otherLink.set('title', "Switch to " + otherLink.get('text') + " login");  
         //          
         //          // Set click linked to active and update form fields
         //          this.addClass('active');
         //          this.set('title', '');  
         //          
         //          Login.theForm.reset();
         //          
         //          // Change the fields
         //          var labels = this.hasClass('admin') ? Login.adminFields : Login.clientFields;
         //          for(var j = 0; j < Login.fields.length; j++) {
         //             if(Login.fields[j].id == 'password') {
         //                try { Login.fields[j].setProperty('type', 'text'); } catch(ex){}
         //             }                    
         //             Login.fields[j].value = Login.fields[j].title = labels[j];
         //          }   
         //             
         //          $('loginType').value = this.hasClass('client') ? 'client' : 'admin';
         //          
         //          
         //          // Hide any existing errors 
         //          Login.hideErrors();
         //          
         //       }
         //    });
         // }
         
         
         // Validate the form onsubmit
         this.theForm.addEvent('submit', function(){
            
            var errorMsg = null;
            if(this.userid.value == '' || this.userid.value == this.userid.title)
               errorMsg = this.userid.title;
            
            if(this.password.value == '' || this.password.value == this.password.title) 
               errorMsg = errorMsg ? errorMsg + ' and password' : 'Password';
            
            // Display the error message if it exists
            if(errorMsg){
            
               errorMsg += ' cannot be blank';
               Login.showErrors(errorMsg);
               return false;            
            }
            
            // Client login type: create a popup and do an AJAX post to populate it
            if(Login.isClient()){
               Login.hide();               
               
               var req = new Request.HTML({url: '/job/login', 
                  onSuccess: function(html) {                     
                     Login.popup.focus();                           
                     var doc = Login.popup.document;
                     doc.title = 'PostSpots Client Dashboard';
                     doc.body.appendChild(new Element('div').adopt(html));                     
                  },
             
                  onFailure: function() {
                     alert('Login request failed');
                  }
               }).post("user="+$('userid').value+"&pass="+$('password').value+"&userFirstName="+$('name').value);               
               
               return false;
            }
            
            // Admin login type: let the form process the login
            return true;
         });
      }   
   }
   
   
   // Determine if it's a client login
   // isClient : function(){
   //    return $('loginType').value == 'client';
   // },
   
   
   // Display error message
   // showErrors : function(errorMsg){
   //    var msgs = $('msgs');
   //    if(msgs) {
   //       msgs.set('text', errorMsg);
   //    } else {
   //       msgs = new Element('div', {
   //          'id' : 'msgs',
   //          'text' : errorMsg
   //       });
   //       msgs.inject(Login.theForm);
   //    }            
   //    msgs.morph({'top': Login.theForm.getSize().y - 23});   
   // },
   
   
   // Hide error message
   // hideErrors : function(){
   //    var msgs = $('msgs');
   //    if(msgs) {
   //       msgs.morph({'top': 100}); 
   //    }
   // }
}


/* 
 * Mouseover/mouseout events for various page elements
 */
var Hover = {


   init : function(){
      
      // Orange header link
      var orangeLink = $$('a.orange');
      if(orangeLink.length > 0){
         orangeLink[0].set('morph', {duration: 250});
         orangeLink[0].addEvent('mouseover', function(){
            this.morph({
               'padding-top': 60,
               'padding-bottom': 20,
               'background-color': '#ff2a00'
            });
         });
         orangeLink[0].addEvent('mouseout', function(){
            this.morph({
               'padding-top': 52,
               'padding-bottom': 14,
               'background-color': '#ff3e00'
            });
         });         
         
      }
      
      // Icon action links
      var actionLinks = $$('ul.actions a');
      for(var i = 0; i < actionLinks.length; i++){
         actionLinks[i].set('morph', {duration: 600});
         actionLinks[i].setStyle('background-position', -300);
         actionLinks[i].addEvent('mouseover', function(){
            this.morph({'background-position': 0});
         }); 
         actionLinks[i].addEvent('mouseout', function(){
            if(!this.hasClass('active'))
               this.morph({'background-position': -300});
         });          
      }
      
      // Featured client links
      var featuredLinks = $$('.featured-client a');
      for(var i = 0; i < featuredLinks.length; i++){
         featuredLinks[i].set('morph', {duration: 250});
         featuredLinks[i].setStyle('background-color', '#e7e7e7');
         featuredLinks[i].addEvent('mouseover', function(){
            this.morph({'background-color': '#ddd'});
         }); 
         featuredLinks[i].addEvent('mouseout', function(){
            if(!this.hasClass('active'))
               this.morph({'background-color': '#e7e7e7'});
         });          
      }      
      
   }


}


var ClientLogos = {
  
  // Path and title for all logo images
  paths : [
    ['img/logos/bang.png', 'Bang Music'],
    ['img/logos/72-and-sunny.png', '72 and sunny'],
    ['img/logos/abc-news.png', 'ABC News'],
    ['img/logos/akqa.png', 'AKQA'],
    ['img/logos/crawford.png', 'Crawford'],
    ['img/logos/cutting-room.png', 'Cutting Room'],
    ['img/logos/marriott.png', 'Marriott'],
    ['img/logos/octopus.png', 'Octopus'],
    ['img/logos/turner.png', 'Turner Entertainment'],
    ['img/logos/tv-land.png', 'TV Land'],
    ['img/logos/tequilamockingbird.png', 'Tequila Mockingbird'],
    ['img/logos/versus.png', 'Versus'],
    ['img/logos/wk.png', 'Weiden + Kennedy'],
    ['img/logos/sugarbox.png', 'Sugarbox'],
    ['img/logos/absolute.png', 'Absolute'],
    ['img/logos/cutwater.png', 'Cutwater'],
    ['img/logos/finalcut.png', 'Final Cut']
  ], 
  toShow : 5,
  
  // Current index in paths array
  currIdx : null,
  interval : null,
  
  /*
   * Sets the logo image sources
   */
  init : function(){
  
  
    var container = $('client-logos'); 
    if(container){
    
      // Preload the images
      var logoImgs = new Asset.images(Utils.arrayMultiToSingle(0, ClientLogos.paths), {onComplete: function(){  
      
      
        // Determine random start index
        ClientLogos.currIdx = Math.floor(ClientLogos.paths.length * Math.random());
    
        // Loop through all the existing imgs and destroy them
        var imgs = container.getElements('img');        
        for(var i = imgs.length - 1; i > -1; i--)
          imgs[i].destroy();
          
        // Recreate the imgs that we just destroyed from our preloaded img array (this prevents img src flicker)
        for(var i = 0; i <= ClientLogos.toShow; i++){        
                    
          logoImgs[ClientLogos.currIdx].set('class', 'l'+(i+1));
          logoImgs[ClientLogos.currIdx].set('alt', ClientLogos.paths[ClientLogos.currIdx][1]);
          logoImgs[ClientLogos.currIdx].set('title', ClientLogos.paths[ClientLogos.currIdx][1]);

          // Inject the image into the DOM and make it appear
          $('scroll').grab(logoImgs[ClientLogos.currIdx]);

          logoImgs[ClientLogos.currIdx].set('opacity', 0);        
          logoImgs[ClientLogos.currIdx].setStyle('visibility', 'visible');
          
          if(i != ClientLogos.toShow)
            logoImgs[ClientLogos.currIdx].morph({'opacity': 1});   
                        
          // Move the current index forward and check for rollover
          ClientLogos.currIdx++
          if(ClientLogos.currIdx == ClientLogos.paths.length)
            ClientLogos.currIdx = 0;             
          
        }
      
        // Setup the scroll behaviour
        ClientLogos.interval = ClientLogos.scroll.periodical(3800, container.getElement('div#scroll'));
        
      }});      
    }  
  },
  
  /*
   * Scrolls a logo into and out of view
   */
  scroll : function(){
    
    var first = this.getElement('img:first-child');
    var last = this.getElement('img:last-child');
    
    // Animate everything
    first.set('morph', {duration: 800});
    first.morph({'opacity': 0});
    last.set('morph', {duration: 2400});
    last.morph({'opacity': 1});    
    
    this.set('morph', {duration: 1500, onComplete: (function(){
      // Move the first child to the end of the list and update its source
      this.grab(first.dispose());    
      first.set('src', ClientLogos.paths[ClientLogos.currIdx][0]);
      first.set('alt', ClientLogos.paths[ClientLogos.currIdx][1]);
      first.set('title', ClientLogos.paths[ClientLogos.currIdx++][1]); 
      first.setStyle('left', last.getStyle('left').toInt() + 116);
    }).bind(this)});    
    this.morph({'left': this.getStyle('left').toInt() - 116});
    

    
    if(ClientLogos.currIdx == ClientLogos.paths.length)
      ClientLogos.currIdx = 0;       
  
  }
}


/* 
 * Attach domready events 
 */
window.addEvent('domready', function(){

   // Setup the Constants object
   Constants.init();

   // Setup the action cluster
   Actions.init();
   
   // Setup the login form
   Login.init();
   
   // Setup the page mouseovers
   Hover.init();
   
   // Scrolling client logo behaviour
   ClientLogos.init();

});