/* Utility Functions */

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

var Altour = {
  debug : false,
  callbacks : {
	  '' : indexCallback,
    'performanceImprovementRewards' : performanceImprovementRewardsCallback,
    'travelEntertainment' : travelEntertainmentCallback,
    'newsletter' : newsletterCallback,
    'contact' : contactCallback,
    'meetingsEvents' : meetingsEventsCallback,
  },
  fetchCallback : function() {
    var pathname = window.location.pathname.substring(1).split('/');

    if(pathname.length === 1) {
      callback_name = pathname[0];
    } else {
      var callback_builder = [];
      for(var i=0;i<pathname.length - 1; i++) {
        var micropath = pathname[i].split('-');
        for( var j = 0; j < micropath.length; j++ ) {
          callback_builder.push(micropath[j]);
        }
      }
      var callback_name = callback_builder.shift();
      for(var k=0; k < callback_builder.length; k++) {  
        callback_name = callback_name + callback_builder[k].capitalize();
      }
    }
    
    if(Altour.debug)
      console.log(['callback_key_name',callback_name]);

    var function_to_call = Altour.callbacks[callback_name] || defaultCallback;
    function_to_call.call();
  },
  userAgent : function(iOs){
  // if iOs parameter is present detect if user agent is iOs.
  if(iOs) {
    if(navigator.userAgent.match(/(iPad|iPhone|iPod)/i))
      return true;
    else
      return false;
  // else detect the user agent
  } else {
    if(navigator.userAgent.match(/iPod/i))
      return 'iPod';
    if(navigator.userAgent.match(/iPhone/i))
      return 'iPhone';
    else if(navigator.userAgent.match(/iPad/i))
      return 'iPad';
    else
      return false;
  }
}


};


/* Function Callbacks */

function indexCallback() {

  if(Altour.debug)
  	console.log('index callback');

  // have to define this so that modified setting can be executed on window.resize
  var slideshow_settings = {
    activePagerClass: 'active',
    after: function(){
      $('.current_slide').removeClass('current_slide');
      $(this).addClass('current_slide');
    },
    cssBefore : {
      left : '-100%',
      right: 'auto'
    },
    cssAfter : {
      left: 0,
      right: 'auto'
    },
    fx: 'scrollHorz',
    next: '#next',
    pager: '#slideshow-buttons' ,
    pagerAnchorBuilder:  function(index, slide) {
      var title = $(slide).attr('rel');
      return '<a href="#" class="button">' + title + '<span></span></a>';
    },
    prev: '#prev',
    slideResize: 1,
    speed: 600,
    timeout: 0,
  }

  $('.slide').width($('#slideshow-container').width());

  $('#slideshow-large').cycle(slideshow_settings); 

   
  $(window).on('resize',function(){
    $('.slide').width($('#slideshow-container').width());

    $('#slideshow-large').cycle('destroy');
    // modified settings set here, the cycle plugin is reinitialized starting from
    // the current slide when the window was resied
    slideshow_settings.startingSlide = $('.current_slide').index();

    var selector_item = $('.slide[display="list-item"]');

    $('#slideshow-large').cycle(slideshow_settings);
  });

  var quote_settings = {
    speed:2000,
    timeout: 10000
  };
  
  $('#quote-widget-quotes').cycle(quote_settings);

}

function newsletterCallback() {

  var isValidEmailAddress = function(emailAddress) {
      var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
      return pattern.test(emailAddress);
  };
  
  //if print newsletter is selected, make "address 1" required
  $('#print_newsletter').click(function(){
     if ($('#print_newsletter').attr("checked")=="checked") {
       $('#hide-address').fadeIn();
       $('#address_1').addClass("required");
       $('#city').addClass("required");
       $('#country').addClass("required");
       $('#postal_code').addClass("required");

     } else {
       $('#address_1').removeClass("required");
       $('#city').removeClass("required");
       $('#country').removeClass("required");
       $('#postal_code').removeClass("required");
       $('#hide-address').fadeOut();

     }
  });
  
  $('#newsletter-form').submit(function(){
    var em = $("#email").val();
    var isValid = true;
    var isChecked = false;
    $("span.error").hide();
    if (isValidEmailAddress(em)) {
      isValid = true;
    } else {
      isValid = false;
      $("#email").parent().find("span.error").first().show();
    }
    
    //checkboxes - at least one is set
    $("input.checkbox").each(function(i,e){
      if ($(e).attr("checked")=="checked") {
        isChecked=true;
      }
    });
    if (!isChecked) {
      $("div.checkbox-error").show();
    }
    /*
    var ex = em[1].split(".");
    var isValid =true;
    if (ex[1].size > 1) {
      isValid = true;
    } else {
      isValid = false;
    }
    alert(isValid);
    return false;
    */
//    isValid=true;
    $("div.error").hide();
    $("input.required").each(function(i,e){
      if ($(e).attr("value").length < 1) {
        $(e).parent().find("span.error").first().show();
        isValid = false;
      }
    });
    if (isValid==true &&( isChecked==true)) {
      isValid=true;
      $("#newsletter-form").fadeOut(400,'easeInQuad', function(){
        $("#response").fadeIn(400);
      });
    }
    if (!isValid || !isChecked) {
      alert("Please complete all required fields");
      isValid=false;
    }
    
    return isValid;
  });
}

function performanceImprovementRewardsCallback() {
  if(Altour.debug)
    alert('performanceImprovementRewardsCallback');

    var slide_count = $('#slideshow-carousel').children().length;
    
    var button_width = Math.floor(($('#subpage-buttons').width() / slide_count) - slide_count + 1);
    console.log(['button_width',button_width]);
    
    $('#slideshow-carousel').cycle({
      activePagerClass : 'active',
      fx: 'scrollHorz',
      height: 335,
      speed:600,
      next: '#next',
      pager : '#subpage-buttons',
      pagerAnchorBuilder : function(index,slide){
        return '<div class="button" style="width:' + button_width + 'px"><div class="gradient">&bull;</div></div>';
      },
      prev: '#prev',
      slideResize: 1,
      timeout: 0,
      width:650,
    });
}


function travelEntertainmentCallback() {
  if(Altour.debug)
    alert('travelEntertainmentCallback');
    
  var slide_count = $('#slideshow-carousel').children().length;
  
  var button_width = Math.floor(($('#subpage-buttons').width() / slide_count) - slide_count + 1);

  if(Altour.debug)
    console.log(['button_width',button_width]);
  
  $('#slideshow-carousel').cycle({
    activePagerClass : 'active',
    fx: 'scrollHorz',
    height: 335,
    next: '#next',
    pager : '#subpage-buttons',
    pagerAnchorBuilder : function(index,slide){
      return '<div class="button" style="width:' + button_width + 'px"><div class="gradient">&bull;</div></div>';
    },
    prev: '#prev',
    slideResize: 1,
    timeout: 0,
    width:650,
    speed:600,
  });  
}

function contactCallback() {
  //$('#submit').click(function(){
    //  $('#contact-form').submit();
  //});

  $('#contact-form').submit(function(){
	var isValidEmailAddress = function(emailAddress) {
        	var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    };
      var isValid=true;
      var em = $("#email").val();
      $("span.error").hide();
      if (isValidEmailAddress(em)) {
        isValid = true;
      } else {
        isValid = false;
        $("#email").parent().find("span.error").first().show();
      }


    $(".required").each(function(i,e){
      if ($(e).val() < 1) {
        $(e).parent().find("span.error").first().show();
        isValid = false;
      }
    });
    if (!isValid) {
       alert("Please complete all required fields");
     }

    //if (isValid==true) {
      //$("#contact-form").fadeOut(400,function(){
       // $("#response").fadeIn(400);
      //});
    //}
      return isValid;
  });
}

function meetingsEventsCallback() {

  // $("div.hotspot").each(function(i,e){

  //   var slide;
  //   $("div.slide").each(function(ii,ee){
  //     if ($(ee).attr("rel")==$(e).attr("rel")) {
  //       slide = ee;
  //     }
  //   });

  //   $(e).hover(function(){
  //     $(e).hide();
  //     $(slide).fadeIn("fast");
  //   });
    
  //   $(slide).click(function(){
  //     $(e).toggle();
  //     $(slide).toggle("fast");
  //   });

  //   $(e).click(function(){
  //     $(e).toggle();
  //     $(slide).toggle("fast");
  //   });

  //   $(slide).mouseout(function(){
  //     $(slide).fadeOut("fast");
  //     $(e).show();
  //   });
  // });

}

function defaultCallback() {
  if(Altour.debug)
    alert('defaultCallback');
}
/* End Function Callbacks */

/**********************************************************************************************************************/

$(window).on('load',function(){
  $('html').removeClass('loading');
});  
        

$(document).on('ready',function(){   

  //add .iOs to the body tag to namespace targeted CSS
  if(Altour.userAgent('iOs')) {
    $('body').addClass('iOs');



    $('.sf-blue > ul > li > a').click(function(event){
      
      event.preventDefault();

      $(this).click(function(){
        
        var href = $(this).attr('href');

        window.location = href;

      });

    });




    
  }

  Altour.fetchCallback();
  
  //image rollovers - to active state
  $(".rollover").each(function(i,e){
      var src = $(e).attr("src");
      var active = src.replace(".png","-active.png");
      $(e).mouseover(function(){
          $(e).attr("src",active);
      });
      
      $(e).mouseout(function(){
          $(e).attr("src",src);
      })
  });

  //image rollovers on the user-editable sidebars are different
  $("#secondary").find(".visit").find("img").each(function(i,e){
      var src = $(e).attr("src");
      var active = src.replace(".png","_hover.png");
      $(e).mouseover(function(){
          $(e).attr("src",active);
      });
      
      $(e).mouseout(function(){
          $(e).attr("src",src);
      })
  })



//make footer links have an active color
// $("#footer").find(".link").each(function(i,e) {
//   //if top page matches link src, change style
//   var link = $(e).find("a");
//   var url = window.location.href.split("/");
//   var ignore =  url[0]+"/"+url[1]+"/"+url[2];
//   if ((ignore+$(link).attr("href")+"/")==window.location.href)
//     $(e).addClass("active");
// });

});

