var TJB = {};

TJB.Setup = {
   imageLink: function(){
      var imageLinks = $$('div.portfolioLink a');
      imageLinks.each(function(el, index){
         el.addEvent('mouseover', TJB.Events.toggleSpan);
         el.addEvent('mouseout', TJB.Events.toggleSpan);
      });
   },
   
   showDetails: function(){
      var detailLink = $$('h1','headerImage');
      var grid = $('gridOverlay');
      grid.on = false;
      detailLink.addEvent('click', TJB.Events.toggleGrid);
      grid.addEvent('click', TJB.Events.toggleGrid);
   },
   
   sliderSetup: function(){
      var mySlider;
      $try(function(){
         mySlider = new ImageSlider({
            objToSlide: 'sliderHolder',
            sliderElements: 'div.sliderImg',
            numOfElementsToSlide: 2, 
            numOfElementsShown: 3, 
            leftBtn: 'slideLeftBtn',
            rightBtn: 'slideRightBtn',
            onSlideComplete: function(index){
               console.info(index);
            }
         });
      });
      var images = $$('a.activeImg');
      images.each(function(el, index){
         el.setStyle('opacity', 0.1);
         var sibling = el.getNext();
         el.addEvent('mouseover',TJB.Events.fadeImage);
         el.addEvent('mouseout',TJB.Events.fadeImage);
         el.addEvent('click',TJB.Events.portfolioClick);
      });
      //Check to see if there is a hash value in the url
      var currentHash = TJB.Utils.getLocationHash();
      var findID;
      if(currentHash){
         //find the imagesLink that corresponds to the current url hash id
         findID = currentHash + 'Link';
         images.each(function(el, index){
            if(el.getParent().id == findID){
               //found it, now set the portfolio section to this
               TJB.Events.setDefaultPortfolio(el, index);
               //slide the images in the header to show the new selected one
               mySlider.slideTo(index);
               return false;
            }
         });
      }else{
         //make the first one active
         TJB.Events.setDefaultPortfolio(images[0]);
      }
   },
   
   injectEmail: function(){
      var holder = $('emailAddress');
      var email;
      var txt;
      if(holder){
         holder.empty();
         email  = new Element('a', {id: 'myFirstElement', href: 'mailto:travis@travisjbeck.com', 'class': 'textLink'});
         email.appendText('travis@travisjbeck.com');
         holder.adopt(email); 
      }
   },
   
   ajaxForm: function(){
      var _form = $('contactForm');
      var ems;
      if(_form){
         _form.addEvent('submit', TJB.Events.submitForm);  
         ems = _form.getElements('em');
         ems.each(function(em, index){
            em.setStyle('opacity', 0);
         });
         $('errorMessage').setStyle('opacity', 0);
         $('errorMessage').addClass('errorMessageStyle');
      }
   }
};

TJB.Events = {
   activeImg: null,
   activeSection: null,
   portfolioHolder: null,
   portfolioSections: null,
   toggleSpan: function(event){
      if(event.type == "mouseover"){
         this.getElement("span").style.display = "block";
      }else{
         this.getElement("span").style.display = "none";
      }
   },
   
   toggleGrid: function(even, el){
      var grid = $('gridOverlay');
      if(grid.on){
         grid.style.display = "none";
         grid.on = false;
      }else{
         grid.style.display = "block";
         grid.on = true;
      }
   },
   
   fadeImage: function(event){
      if(event.type == "mouseover"){
         this.fade('in');
      }else{
         if(!this.retrieve('active')){
            this.fade(0.1);
         }
      } 
   },
   
   portfolioClick: function(event){
      event.stop();
      if(this.retrieve('active')){return false;};
      var oldActive;
      if(TJB.Events.activeImg){
         TJB.Events.activeImg.store('active', false);
         TJB.Events.activeImg.fade(0.1);
      }
      TJB.Events.activeImg = this;
      this.store('active', true);
      var linkID = this.getParent().id;
      var newSectionID = linkID.replace(/Link/g, "Details");
      TJB.Events.loadPortfolio(newSectionID);
   },
   
   loadPortfolio: function(sectionID){
      var foundSection = TJB.Utils.findDetailSection(sectionID, portfolioSections);
      var newSection = foundSection.section.clone();
      //inject the cloned section
      portfolioHolder.adopt(newSection);
      //make the new section visible and place off the screen to the right
      newSection.setStyle('position', 'absolute');
      newSection.setStyle('display', 'block');
      newSection.setStyle('left', portfolioHolder.getSize().x);
      newSection.setStyle('width', portfolioHolder.getSize().x);
      var newHeight = foundSection.height;
      var slideIn = new Fx.Morph(newSection, {duration: 300, easing: Fx.Transitions.Expo.easeInOut});
      slideIn.addEvent('complete', function() {
         //cleanup
         activeSection.dispose();
         activeSection = newSection;
      }); 
      //fade out current section
      activeSection.fade('out');
      //slide in new section
      slideIn.start({
         left: 0
      });
      //resize the window height
      var myFx = new Fx.Tween(portfolioHolder);
      myFx.start('height', newHeight + "px");
      TJB.Utils.reInitModalViewer(newSection);
      //set url hash to current portfolio item
      TJB.Utils.setLocationHash(sectionID);
   },
   
   setDefaultPortfolio: function(obj, indexID){
      if(!obj){return false;}
      var index = indexID || 0;
      obj.fade('in');
      TJB.Events.activeImg = obj;
      obj.store('active', true);
      //grab and hide all the portfolio sections
      portfolioSections = $$('div.portfolioSection');
      portfolioSections.each(function(section, index){
         section.store('height', section.getSize().y);
         section.setStyle('display', 'none');
      });
      //clone and inject the first and active portfolio section into the portfolio window
      activeSection = portfolioSections[index].clone();
      activeSection.setStyle('display', 'block');
      activeSection.setStyle('position', 'absolute');
      portfolioHolder = $('portfolioWindow');
      portfolioHolder.setStyle('height', portfolioSections[index].retrieve('height'));
      portfolioHolder.adopt(activeSection);
      //re-invoke image viewer
      TJB.Utils.reInitModalViewer(activeSection);
   },
   
   submitForm: function(event){
      event.stop();
      ems = this.getElements('em');
      ems.each(function(em, index){
         em.fade(0);
      });
      var btn = $('submitBtn').getElement('input');
      var spinner = $('submitBtnLoading');
      var sent = $('submitBtnSent');
      var sentMsg = $('messageSent');
      var errorMsg = $('errorMessage');
      var theForm = this;
      btn.style.display = 'none';
      spinner.style.display = 'block';
      errorMsg.fade(0);
      //validate
      var valid = TJB.Utils.validateForm();
      if(valid){
         this.set('send', {
            onSuccess: function(response){
               spinner.style.display = 'none';
               sent.style.display = 'block';
               sent.setStyle('opacity', 1);
               btn.style.display = 'block';
               btn.setStyle('opacity', 0);
               sentMsg.setStyle('opacity', 0);
               sentMsg.style.display = 'block';
               theForm.reset();
               sentMsg.fade(1);
               //google pageview code
               pageTracker._trackPageview('/contactFormSubmitted');
               (function(){
                  sent.fade(0);
                  btn.fade(1);
                  sentMsg.fade(0);
               }).delay(10000);
            },
            
            onFailure: function(response){
               btn.style.display = 'block';
               spinner.style.display = 'none';
               errorMsg.empty();
               errorMsg.appendText('Network error, please try again.');
               errorMsg.fade(1);
            }
         });
         this.send();
      }else{
         btn.style.display = 'block';
         spinner.style.display = 'none';
      }
   }
};

TJB.Utils = {
   
   findDetailSection: function(id, objArry){
      var retObj = {};
      objArry.each(function(section, index){
         if(section.id == id){
            retObj.section = section;
            retObj.height = section.retrieve('height');
            return;
         }
      });
      return retObj;
   },
   
   reInitModalViewer: function(obj){
      var _links = $$('a[rel^=shadowbox]');
      Shadowbox.setup(_links);
   },
   
   setLocationHash: function(id){
      var newHash = id.replace(/Details/g, '');
      location.hash = newHash;
   },
   
   getLocationHash: function(){
      return location.hash.substr(1);
   },
   
   isValidEmail: function(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   return false;
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}
      if (str.indexOf(at,(lat+1))!=-1){
         return false;
      }
      if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
         return false;
      }
      if (str.indexOf(dot,(lat+2))==-1){
         return false;
      }
      if (str.indexOf(" ")!=-1){
         return false;
      }
      return true;	
   },
   
   validateForm: function(){
      var valid = true;
      if(!($('from_name').value.length > 0)){
         valid = false;
         $('from_name').getNext().empty().appendText('* Required').fade(1);
      }
      
      if(!($('from_address').value.length > 0)){
         valid = false;
         $('from_address').getNext().empty().appendText('* Required').fade(1);
      }else{
         var txt = $('from_address').value;
         if(!TJB.Utils.isValidEmail(txt)){
            valid = false;
            $('from_address').getNext().empty().appendText('* Invalid Email').fade(1);
         }
      }
      if(!($('comment').value.length > 0)){
         valid = false;
         $('comment').getNext().empty().appendText('* Required').fade(1);
      }  
      return valid;
   },
   
   googleTrack: function(obj){
      var fullContent = obj.content;
      var content
      if (fullContent.indexOf('.com')>0){
         var content = fullContent.substr(fullContent.indexOf('.com')+4);
      }else{
         content = fullContent;
      }
      pageTracker._trackPageview(content);
   }
   
};

TJB.Mail = {
   //this is to avoid email spam harversting robots.
   tld_: ["com","org", "net", "ws", "info", "co.uk", "org.uk", "gov.uk", "ac.uk"],
   topDom_: 13, 
   m_: "mailto:",
   a_: "@",
   d_: ".",
   mailTo: function(name, dom, tl, params, obj){
      var display = name+this.a_+dom+this.d_+this.tld_[tl];
   	var href = this.m_+display;
   	document.write('<a href="'+href+'"'+params+'">'+display+'</a>');
   }
};

window.addEvent('domready', function(){
   $try(function(){
      setupZoom();
   });
   
   var options = {
      onOpen: TJB.Utils.googleTrack,
      animSequence: 'sync'
   };
   
   $try(function(){
      Shadowbox.init(options);
   });
   
   TJB.Setup.imageLink();
   //TJB.Setup.showDetails(); //gridOverlay
   TJB.Setup.sliderSetup();
   TJB.Setup.ajaxForm();
   TJB.Setup.injectEmail();

});
