// stuff that only needs the dom
$(document).ready(function() {
   
   // search button behavior
   $('#searchform div.submit').click(function(){
      if($('#searchform input').val() != '')
         $('#searchform').submit();
      else{
         $('#searchform div.input').stop(true, true).effect("highlight", {}, 2000);
         $('#searchform input').stop(true, true).effect("highlight", {}, 2000).focus();
      }
   });
   
   var signup = $('div.signup_container');
   // signup button behavior
   signup.find('div.submit').click(function(){
      var emailVal = String(signup.find('div.email input').val())
      var email = emailVal.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i);
      
      var postcodeVal = String(signup.find('div.number input').val())
      var postcode = postcodeVal.match(/^\d\d\d\d$/);
      
      if(email && postcode){
         signup.find('div.submit').addClass('loading');
         $.ajax({
            url: "/signup",
            data: {
               email: emailVal,
               postcode: postcodeVal
            },
            context: signup,
            success: function(){
               $(this).find('div.submit').removeClass('loading').html('Success!');
               signup.find('div.email input').val('');
               signup.find('div.number input').val('');
               $(this).find('div.submit').stop(true, true).effect("highlight", { color: '#009900' }, 2000);
            },
            error: function(){
               $(this).find('div.submit').removeClass('loading').html('Error!');
               $(this).find('div.submit').stop(true, true).effect("highlight", { color: '#990000' }, 2000);
            }
         });
         return true;
      }
      if(!postcode){
         signup.find('div.number').stop(true, true).effect("highlight", {}, 2000);
         signup.find('div.number input').stop(true, true).effect("highlight", {}, 2000).focus();
      }
      if(!email){
         signup.find('div.email').stop(true, true).effect("highlight", {}, 2000);
         signup.find('div.email input').stop(true, true).effect("highlight", {}, 2000).focus();
      }
   });
   
   // menu behavior
   $('nav.products').menuify();
   
   // styling
   $('footer nav').equalHeight();
   $('footer').minimumHeight({min: 111});
   $('nav.products > ul').centerFloatedLIs({
      target: '> li > a > div',
      padding_at_bounds: false
   });
   
   // the ul is positioned absolutely so it needs a width in px set.
   // the menu's columns however are dynamic so we can't do this in the css
   $('nav.products li.custom > ul').css({
      'width': (parseInt($('nav.products li.custom ul').css('width')) * $('nav.products li.custom > ul > li').length) + 'px'
   });
   
   $('body.enquiry div.body-inner form').formify();
   $('#form1[name="Order_Customer"]').formify();
   
   var showAll = function(idx, e){
      // append a Show All link to the navigation
      $(e).find('.page_navigation').append('<a class="showall_link" href="">Show All</a>');
      $(e).find('.page_navigation .showall_link').click(function(ee) {
         ee.preventDefault();
         $(e).find('.page_navigation a.active_page').removeClass('active_page');
         $(e).find('.page_navigation a.showall_link').addClass('active_page');
         $(e).find('.content > *').css({'display': 'block'});
      });
      // add a click handler to all navigation links that brings the screen up to the top of the list.
      $(e).find('.page_navigation a').click(function(){
         window.location.hash = '#products_top';
      })
   };
   // normal product page
   $('.productList .products').pajinate({
      items_per_page: 30
   }).each(showAll);
   // new items product page
   $('.newItems > .products').pajinate({
      items_per_page: 32
   }).each(showAll);
});
// stuff that expects the page to fully load
$(window).load(function() {
   if($('.slideshow').length > 0){
      $('.slideshow').blinds({
         rotate: true,
         rotate_interval: 3000,
         links: true,
         width: 890,
         height: 365,
         h_res: 1,
         tile_orchestration: function (i, j, total_x, total_y) {
            return 300;
         }
      });
      // In order to avoid a visual artifact in ie 7-8-9 we need to invoke the change method straight away.
      $('.slideshow').blinds_change(0);
   }
   $('div.controls > div.add').minimumWidth({min: 131});
   
   // carousel
   carouselSetup();
   
   // will redirect to the correct site if necessary
   checkCookies();
});

function checkCookies() {
   // sa will be the default site.
   // landing on any lecornu site for the first time will trigger the state popup
   var sa = 'http://sa.lecornu.com.au/';
   var nt = 'http://nt.lecornu.com.au/';
   var cookieDomain = 'lecornu.com.au';
   
   // These are the urls that the map plugin points you to when you click on the states
   // The are also used to redirect you if you are on the wrong site
   var redirlocations = {
      sa : sa,
      wa : sa,
      qld: sa,
      act: sa,
      nsw: sa,
      vic: sa,
      tas: sa,
      nt : nt
   }
   // checking site location
   var hash = window.location.hash.replace('#', '').split('=');
   if(hash.length > 0 && hash[0] == 'loc' && $.cookie('lecornu-location') != hash[1])
      $.cookie('lecornu-location', hash[1], { path: '/', domain: cookieDomain, expires: 365 });
   
   if(!$.cookie('lecornu-location') && window.location.hostname.indexOf(cookieDomain) > -1){
      $(window).mapify(redirlocations, cookieDomain);
   } else {
      // only redirect if we land on lecornu.com.au
      if(window.location.hostname.replace(/^www\./i, '') == cookieDomain){
         var loc = redirlocations[$.cookie('lecornu-location')];
         var locHostName = loc.replace('http://', '').split('/');
         if(locHostName.length > 0) locHostName = locHostName[0];
         if(locHostName.match(':')) locHostName = locHostName.split(':')[0];
         var currentLoc = window.location.hostname.replace('http://', '').split('/');
         if(currentLoc.length > 0) currentLoc = currentLoc[0];
         if(locHostName && currentLoc){
            // If the current hostname is different to the one corresponding to a users loc, redirect.
            var currentLocWWW = currentLoc.replace('www.', '');
            var port = window.location.port ? ':' + window.location.port : '';
            if(locHostName != currentLoc && locHostName != currentLocWWW){
               window.location = 'http://' + locHostName + port + window.location.pathname + window.location.search;
            }
         }
      }
   }
}

function addToCart(url, el){
   el = $(el.parentNode);
   el.addClass('loading');
   
   var img = el.find('img');
   img.hide();
   
   $.ajax({
      url: url,
      success: function(){
         el.removeClass('loading');
         img.show();
      },
      error: function(){
         el.removeClass('loading');
         img.show();
      }
   });
   
   return true;
}

function carouselSetup(){
   $('#viewport').carousel('#previous', '#next');
   
   // positioning the nav buttons
   var nav = $('#viewport .linkbox');
   if(nav.length == 2){
      $(nav[0]).css({
         'left': '0px',
         'top': ($('#viewport').height() / 2) - ($(nav[0]).height() / 2) + 'px'
      });
      $(nav[1]).css({
         'left': $('#viewport').width() - $(nav[1]).width(),
         'top': ($('#viewport').height() / 2) - ($(nav[1]).height() / 2) + 'px'
      })
   }
   
   // hide/show the nav buttons on mouse over/out, buffer for 1/4 of a second
   var tickerTimer;
   var showing = false;
   $('#viewport').mouseover(function(){
      window.clearTimeout(tickerTimer);
      if(!showing){
         showing = true;
         $(nav[0]).show("slide", { direction: "right" }, 250);
         $(nav[1]).show("slide", { direction: "left" }, 250);
      }
   })
   $('#viewport').mouseout(function(){
      if(showing){
         window.clearTimeout(tickerTimer);
         tickerTimer = window.setTimeout(function(){
            showing = false;
            $(nav[0]).hide("slide", { direction: "right" }, 250);
            $(nav[1]).hide("slide", { direction: "left" }, 250);
         }, 250);
      }
   })
   
   // The auto-scrolling function
   function slide(){
      $('#viewport #next').click();
   }
   
   // Scroll every 5 seconds
   var intervalId = window.setInterval(slide, 3000);

   // On user click reset the autoscroll interval
   $('#viewport #previous, #viewport #next').click(function(event){
      if(event.originalEvent){
         window.clearInterval(intervalId);
         intervalId = window.setInterval(slide, 3000);
      }
   });
}

