/*global jQuery,window,$ */
/** @namespace */
var ibc = (ibc !== null || ibc !== undefined) ? window.ibc || {} : ibc;
/**
 * @namespace Core functions and variables
 */
ibc.core = {

  nav_index : 0, // index of active nav element
  subnav_trigger : '',  // element that triggered subnav
  forms : [], // array of forms to be validated

  // execute core methods etc
  init : function () {
    $('.outerWrapper').hide();
    this.buildAndCallUrl();
    this.bindNav();
    this.setUpSubnav();
    this.setUpformValidator();
    this.setUpCarousels();
    this.getWeather();
    $('.accessNone').css({'display' : 'block'});
    $('.accessHide').css({'visibility' : 'visible'});
  },

  // convert url like : '/our-brands/vonu-eight/' to element id like : 'vonu_eight' also update meta title
  urlConvert : function (url) {
    var parts,
      id,
      new_title;
    if (url === '/') {
      id = "welcome";
      new_title = "Welcome";
    } else {
      parts = url.substring(0, url.length - 1).split('/');
      id = (parts[parts.length - 1]).replace('-', '_');
      new_title = (parts[parts.length - 1]).replace('-', ' ');
      new_title = new_title.toLowerCase().replace(/\b([a-z])/gi, function (c) {
        return c.toUpperCase();
      });
    }
    new_title = document.title.split('|')[0] + ' | ' + new_title;
    return {'ident' : id, 'title' : new_title};
  },

  // clear form validation
  resetForms : function () {
    var len = ibc.core.forms.length,
      i;
    for (i = 0; i <  len; i += 1) {
      ibc.core.forms[i].resetForm();
    }
  },

  // pull in weather
  getWeather : function () {
    var api_url = 'http://' + document.location.host + '/inc/weather-api.php';
    $.ajax({
      url: api_url,
      dataType : 'json',
      success : function (data) {
        // update weather elements
        $('#weather #cur #temp').text(data.temp);
        // build weather icon file name
        var weather_icon = data.cond;
        weather_icon = weather_icon.replace(/\s/g, '');
        // make it a night time icon
        if (data.daytime === false) {
          weather_icon += '-night';
        }
        // update the image
        $('#weather #cond img').attr({
          src : '/i/icons/' + weather_icon + '.png',
          alt : data.cond
        });
        $('#weather').fadeIn(3000);
      },
      // fail silently on error (results in no weather displayed)
      error : function () {
        return false;
      }
    });
  },

  // retrieve the content for the given url and inject into DOM
  getPageContent : function (content_url) {
    $.ajax({
      url : content_url,
      async : false,
      cache : false,
      dataType : 'html',
      success : function (data) {
        // append content to the DOM
        $(data).insertAfter('.outerWrapper:first').hide();        
      },
      error : function () {
        return false;
      }
    });
  },

  // build urls (from the nav) to be called via ajax
  buildAndCallUrl : function () {
    var urls = [],
      len,
      i;
    $('ul#nav a').each(function () {
      var url = $(this).attr('href');
      // push url onto array only if it doesn't match current path, also handles 'index.php'
      if (url !== document.location.pathname.split('index.php')[0] && url !== document.location.pathname) {
        urls.push($(this).attr('href') + 'content.php');
      }
    });
    // de-dupe the array
    urls = $.grep(urls, function (v, k) {
      return $.inArray(v, urls) === k;
    });
    len = urls.length;
    for (i = 0; i < len; i += 1) {
      // make request
      this.getPageContent(urls[i]);
    }
  },

  // setup the navigation with jquery.address
  bindNav : function () {
    // initialise the address plugin
    $.address.state('/').init(function () {
      $('ul#nav li a, ul#subnav li a, a.ajaxLink').address();
    }).change(function () {
      var value = $.address.value($(this).attr('href')),
        page_to_show = ibc.core.urlConvert(value).ident;
      // fade the page in
      $('.outerWrapper').hide();
      $('#' + page_to_show).fadeIn(250);
      // update the page title
      document.title = ibc.core.urlConvert(value).title;

      // if it's a brands page expand the subnav
      if (value.indexOf('brands') !== -1) {
        $('li').removeClass('selected');
        $('li#brands').addClass('selected');
        ibc.core.expandSubnav(null);
      } else {
        // retract the subnav and update active nav item
        ibc.core.retractSubnav(null);
        $('ul li:not(:#logo) a').each(function () {
          if ($(this).attr('href') === value) {
            $(this).parent('li').addClass('selected');
          } else {
            $(this).parent('li').removeClass('selected');
          }
        });
      }
      // animated scroll to top if not already there
      if ($(window).scrollTop() !== 0) {
        $(window).scrollTo(0, 500);
      }
      // reset any validation errors
      ibc.core.resetForms();
    });
  },

  // slidedown sub nav menu
  expandSubnav : function (e) {
    $('ul li#brands a span span').css({'backgroundPosition' : 'center -7px'});
    $('.outerWrapper').animate({
      top : 290
    }, 200);
    $('#footer').animate({
      top : 290
    }, 200);
    $('#subnav').animate({
      top : 108,
      easing : 'easeInOutQuad'
    }, 300);
    // update var element that triggered hover
    if (e !== null) {
      ibc.core.subnav_trigger = e.currentTarget.id;
    }
  },

  // slideup sub nav menu
  retractSubnav : function (e) {
    // only retractSubnav if it's the same element that triggered the hover
    if (e !== null && ibc.core.subnav_trigger !== e.currentTarget.id) {
      return false;
    } else {
      $('ul li#brands a span span').css({'backgroundPosition' : 'center 0'});
      $('.outerWrapper').animate({
        top : 0
      }, 300);
      $('#footer').animate({
        top : 0
      }, 300);
      $('#subnav').animate({
        top : -310,
        easing : 'easeInOutQuad'
      }, 300);
    }
  },

  // brands sub nav hover and sub menu behaviour
  setUpSubnav : function () {
    var subnav_config = {
      over: this.expandSubnav, // function = onMouseOver callback (required)
      timeout: 750, // number = milliseconds delay before onMouseOut
      out: this.retractSubnav // function = onMouseOut callback (required)
    },
      subnav = $('li#brands ul#subnav').clone();
    $('li#brands ul#subnav').remove();
    $(subnav).insertAfter('#nav').css({'top' : '-1px'});
    $('li#brands, ul#subnav').hoverIntent(subnav_config);
  },

  // configure and bind different carousel types
  setUpCarousels : function () {
    // banner carousel
    $('#banner').cycle({
      fx : 'scrollHorz',
      cleartype : true,
      next : '#banner_next',
      prev : '#banner_prev',
      pause : 1,
      timeout : 4000,
      easing : 'easeInOutExpo'
    });
    // poster and image carousels
    $('.sideCarouselWrapper').each(function () {
      var carousel_id = '#' + $(this).attr('id');
      $(carousel_id + ' .sideCarousel').cycle({
        fx : 'scrollHorz',
        cleartype : true,
        pause : 1,
        timeout : 4000,
        easing : 'easeInOutExpo',
        next : carousel_id + ' .cycleRight',
        prev : carousel_id + ' .cycleLeft',
        before : function () {
          // fade out the caption
          $(carousel_id + ' .caption').fadeOut();
        },
        after : function () {
          // update the caption (image alt value)
          $(carousel_id + ' .caption').text(this.alt).stop().fadeIn();
        }
      });
    });
    // 'ticker' carousels (twitter etc)
    $('.tickerCarouselWrapper').each(function () {
      var carousel_id = '#' + $(this).attr('id');
      $(carousel_id + ' .tickerCarousel').cycle({
        fx : 'scrollHorz',
        cleartype : true,
        timeout : 0,
        delay : -1000,
        next : carousel_id + ' .cycleRight',
        prev : carousel_id + ' .cycleLeft',
        before : function (current, next) {	
          // fade out the current slide
          $(current).css({'visibility' : 'visible'}).fadeOut();
        },
        after : function (next) {
          // fade in the next slide
          $(next).css({'visibility' : 'visible'}).fadeIn();
        }
      });
    });
  },

  // set up form validation rules and messages for each form
  setUpformValidator : function () {
    var tmp_form;
    $('form.validate').each(function () {
      tmp_form = $(this).validate({
        rules : {
          // careers form
          ca_email : {
            required : true,
            email : true
          },
          // contact form
          co_email : {
            required : true,
            email : true
          }
        },
        messages : {
          // careers form
          ca_position : 'Please enter job position',
          ca_name : 'Please enter your name',
          ca_email : {
            required : 'Please enter your email address',
            email : 'Please enter a valid email address'
          },
          // contact form
          co_name : 'Please enter your name',
          co_email : {
            required : 'Please enter your email address',
            email : 'Please enter a valid email address'
          }
        }
      });
      // update forms array
      ibc.core.forms.push(tmp_form);
    });
  }

};

ibc.core.init();




