/***********************
*  Site Specific JS   *
************************/

function defaultmap() {
  var myLatlng = new google.maps.LatLng(-21.14494, 149.18955);
  var mapOptions = {
    zoom: 13,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  
  if($('#default-map').length > 0) {
      var map = new google.maps.Map(document.getElementById('default-map'), mapOptions);
    
      var marker = new google.maps.Marker({
          position: myLatlng,
          map: map 
      });
      
      google.maps.event.addDomListener(window, 'resize orientationchange', function() {
        map.setCenter(myLatlng);
      });    
  }
}
$(window).load(function(){
  defaultmap();
  
  //video
  $('#video1').append('<iframe width="560" height="315" src="https://www.youtube.com/embed/NjH9v9TAyNg?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>');
	/*$('#videoBox').prepend('<video autobuffer loop autoplay muted><source src="https://www.dropbox.com/s/h28tsyrcjnuj9ma/MACKAYSKINCLINIC.mp4?dl=0" type="video/mp4"></video>');*/
	
  //Isotope
  var $container = $('#grid-box').isotope({
    "itemSelector": ".grid",
    masonry: {
      columnWidth: ".grid"
    }
  });
});

function isElementInViewport(el) {
    // special bonus for those using jQuery
    if(el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();
    var isFullySeen = (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
    
    return isFullySeen;
}

function addSubNav(navItem) {
  var url = $(navItem).children('a').attr('href');
  var subNavRef = '.page-map .square-li';
  $.post(url, function(data) {
    var subNav = $(subNavRef, data);
    $.each(subNav.children('li'), function(idx, li) {
      var anchor = $(li).children('a');
      var href = anchor.attr('href');
      
      if( href[0] == '#' ) {
        anchor.attr('href', (url + href));
      } else if( href[0] == '/' ) {
        return;
      }
    });
    
    if(subNav.length) {
      $(navItem).addClass('dropdown').children('a').addClass('dropdown-toggle');
      subNav.removeClass('square-li').addClass('dropdown-menu').appendTo($(navItem));
    }
  }, "html");
}

function adjustNavItem() {
  $.each($('.nav li'), function(idx, li) {
    if($(li).children('a').text() == 'Facials & Peels') {
      //$(li).children('a').html('Facials &<br/> Peels');
      addSubNav(li);
    } else if($(li).children('a').text() == 'Skin Care & Body') {
      //$(li).children('a').html('Skin Care &<br/> Body');
      addSubNav(li);
    } else if($(li).children('a').text() == 'Advanced Therapy & IPL') {
      //$(li).children('a').html('Advanced Therapy &<br/> IPL');
      addSubNav(li);
    } else if($(li).children('a').text() == 'About Us & Contact') {
      //$(li).children('a').html('About Us &<br/> Contact');
      addSubNav(li);
    }
  });  
}

function applyAffixAndSpy() {
  var headerLogoAndContact = $('header .headerLogoAndContact');
  var headerSliderAndNav = $('header .headerSliderAndNav');
  var sections = $('.content-area .section');
  var sectionTitles = $('.content-area .sectionTitle');
    
  // apply affix  
  $(".page-map").affix({
    offset: {
      top: function() {        
        return ( headerLogoAndContact.height() + headerSliderAndNav.height() );
      }
    }
  });
  
  // apply spy
  $(window).scroll(function() {
    var index = -1;
    $.each(sections, function(idx, section) {
      if( isElementInViewport(section) ) {
        index = idx;
        return;
      }

    });
    if(index == -1) {
      $.each(sections, function(idx, section) {
        if( isElementInViewport($(section).find('.sectionTitle')) ) {
          index = idx;
          return;
        }
      });  
    }
    
    if(index > -1)
      $('.page-map .square-li li').removeClass('active').eq(index).addClass('active');
  });  
}

$(document).ready(function() {
  $.favicon('http://cdn.myld.com.au/2/131/just-magic-skin-care-clinic_8769a8adbb.ico');
  $('#error').wrap('<div id="content"><div class="row"><div class="content-area"></div></div></div>');
  $('#content').insertBefore($('.main-footer'));
  $('#shopBtn').prependTo($('#slider'));
  $('#bookBtn').prependTo($('#slider'));
  $('#giftBtn').prependTo($('#slider'));
  
  var clone = $('.navbar ul.nav').clone();
  clone.removeClass('nav').appendTo($('#footer-nav'));
  //$('header .navbar-placeholder .navbar .nav').addClass('nav-justified');
  
  adjustNavItem();
  applyAffixAndSpy();
    
  menu.contactDetails({
    phone: '0749575605',
    email: 'just_magic@bigpond.com',
    address: '17 Sydney Street, Mackay QLD 4740',
    hours: [ 
      [ 'Monday', '9am - 5pm' ],
      [ 'Tuesday', '9am - 5pm' ],
      [ 'Thursday', '9am - 7pm' ],
      [ 'Friday', '9am - 6:30pm' ],
      [ 'Saturday', '8am - 12noon' ]      
    ]
  }); 
  
  $('.tooltipster').tooltipster({
    offsetY: 2,
    animation: 'grow',
    position: 'left'
  });
  
  jQuery('.camera_wrap').camera({
     random: true,
     navigation: false,
     pagination: false,
     navigationHover: false,
     playPause: false,
     autoAdvance: false,
     mobileAutoAdvance: false,
     loader: 'none',
     height: '400px'
  }); 
  
  if(window.location.hash) {     
    var offset = $(window.location.hash).offset();
    $('html, body').animate({
      scrollTop: offset.top,
      scrollLeft: offset.left
    }, 1000);
  }
  
  $('.faq-list').goFaq();
  
  if( Modernizr.touch && $(".fancybox").length > 0 ) { 
   var myPhotoSwipe = $(".fancybox").photoSwipe({ enableMouseWheel: false , enableKeyboard: false });
  } else {
    /* Apply to single image */
    $("a.fancybox").fancybox();

   /* Apply fancybox to multiple items */
    $("a.fancybox[rel='gallery_group']").fancybox({
      'transitionIn'    :    'elastic',
      'transitionOut'    :    'elastic',
      'speedIn'        :    600, 
      'speedOut'        :    200 
    });
    $("a.fancybox[rel='gallery_group2']").fancybox({
      'transitionIn'    :    'elastic',
      'transitionOut'    :    'elastic',
      'speedIn'        :    600, 
      'speedOut'        :    200 
    });
  }
  
  $('#newsletter_form').formValidation({ 
    validateText: ["firstname", "surname"],
    validateEmail: ["email"],
    validateSpam: true
  });
  
  $('#gift_voucher_form').formValidation({ 
    validateText: ["name", "phone", "gift_voucher_value"],
    validateEmail: ["email"],
    validateSpam: true
  });
  
  $('#contact_form').formValidation({ 
    validateText: ["firstname", "lastname", "mobile"],
    validateDropdown: ["preferred_day", "preferred_time"],
    validateRadiobutton: ["radiogroup_gender"],
    validateEmail: ["email"],
    validateSpam: true
  });
  
  $('#contact_us_form').formValidation({ 
    validateText: ["firstname", "surname", "phone"],
    validateEmail: ["email"],
    validateSpam: true
  });
});



//
//Just Magic Skin Care Clinic - Blogger v3 News Feed Generator
//
// Returns a long month string based on an Int input of range 0-11 (received from a Date.getMonth() return)
function numToMonth(num) {
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return months[num];
}
 
// Returns a short month string based on an Int input of range 0-11 (received from a Date.getMonth() return)
function numToShortMonth(num) {
        var month = '';
        switch (num) {
            case 0:
                month = "Jan";
                break;
            case 1:
                month = "Feb";
                break;
            case 2:
                month = "Mar";
                break;
            case 3:
                month = "Apr";
                break;
            case 4:
                month = "May";
                break;
            case 5:
                month = "Jun";
                break;
            case 6:
                month = "Jul";
                break;
            case 7:
                month = "Aug";
                break;
            case 8:
                month = "Sep";
                break;
            case 9:
                month = "Oct";
                break;
            case 10:
                month = "Nov";
                break;
            case 11:
                month = "Dec";
                break;
        }
        return month;
    } // End function numToShortMonth(num)
 
// ************************************
// Change variabls here
// ************************************
if ($('#blog').length) {
  var blog_id = "7323821552291813135"; // Put BLog ID here
  var api_key = "AIzaSyBvGn7mS6Li8LXQogsu9XfGNz9m_oDLo-g"; // Put API Key here
  console.log("Blog page") // Debug
}

// Create URL from variables above
var just_magic_blog_api_string = 'https://www.googleapis.com/blogger/v3/blogs/'+blog_id+'/posts?key='+api_key;
var just_magic_blog_jqHXR = $.getJSON(just_magic_blog_api_string) // We will be using this plenty later on
 
.done(function(just_magic_blog_JSON) {
        if ($('#blog').length) { // If we're on the Blog page
            $.each(just_magic_blog_JSON.items, function(i, just_magic_blog_item){ //Loop through each blog post
              var post_id = just_magic_blog_item.id //Use the Post ID as a unique identifier
              var published_date = new Date(Date.parse(just_magic_blog_item.published)); //Parse the JSON string to get published_date (v3 uses ECMAScript 5 ISO-8601 format) to Date prototype
              var published_month = numToShortMonth(published_date.getMonth()); //Get a short month String based off the Date prototype - getMonth returns an Int of range 0-11
              if (i === 0) { //first item
                $('<div role="tabpanel" class="tab-pane active" id="blogFeedItem' + post_id + '"><div class="blogDate">Posted: ' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</div><h3 itemprop="name">' + just_magic_blog_item.title + '</h3>' + just_magic_blog_item.content + '</div>').appendTo('#blogFeed');
                $('<li role="presentation" class="active"><a href="#blogFeedItem' + post_id + '" role="tab" data-toggle="tab"><span class="blogDateSub">' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</span>' + just_magic_blog_item.title + '</a></li>').appendTo('#blogNavTab ul');
                $('#blogFeedItem' + post_id + ' a > img').parent().attr('rel', 'blogFeedItem' + post_id);
                $('#blogFeedItem' + post_id + ' a > img').parent().addClass('fancybox');
 
              } else { // the other stuff
                $('<div role="tabpanel" class="tab-pane" id="blogFeedItem' + post_id + '"><div class="blogDate">Posted: ' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</div><h3 itemprop="name">' + just_magic_blog_item.title + '</h3>' + just_magic_blog_item.content + '</div>').appendTo('#blogFeed');
                $('<li role="presentation" class=""><a href="#blogFeedItem' + post_id + '" role="tab" data-toggle="tab"><span class="blogDateSub">' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</span>' + just_magic_blog_item.title + '</a></li>').appendTo('#blogNavTab ul');
                                 
                                $('#blogNavTab ul li').hide();
                                var size_li = $("#blogNavTab ul li").size();
                                var x=10;
                                $('#blogNavTab ul li:lt('+x+')').show();
                                $('#loadMore a').click(function () {
                                        x= (x+10 <= size_li) ? x+10 : size_li;
                                        $('#blogNavTab ul li:lt('+x+')').show();
                                        //if(x == size_li){
                                        //      $('#loadMore a').hide();
                                        //}
                                        return false;
                                });
                $('#blogFeedItem' + post_id + ' a > img').parent().attr('rel', 'blogFeedItem' + post_id);
                $('#blogFeedItem' + post_id + ' a > img').parent().addClass('fancybox');
              }
            });
            $('.blogDate').css({
                'color': '#f26329',
                'font-size': '26px',
                'font-weight': '300',
                'line-height': 'normal'
              }); //In-line CSS styling for .blogDate required as the class is not being recognised by browsers
            $('a.fancybox[rel*="blogFeedItem"]').fancybox();
            var hash = window.location.hash;
            if (hash !== '') {
              $('#blogNavTab a[href="' + hash + '"]').tab('show');
              $('html, body').delay(500).animate({
                scrollTop: $(hash).offset().top - 191
              }, 2000);
            }
        }
        // end of news page
    }) //End .done
//Fallback content to be displayed in case the blog is offline; not responding; or over the limit of daily requests
.fail(function() {
  if ($('#home').length) {
    $("#newsContent").html($("#newsFailTemplate").render());
  }
  if ($('#news-links').length) {
    $.each(just_magic_blog_JSON.items, function(i, just_magic_blog_item) {
      $('<h1 itemprop="name">News Currently Offline</h1><p item="description">Apologies, the news feed is currently offline. Please contact our staff so we can diagnose and resolve the issue as soon as possible!</p>').appendTo('#blogFeed');
    });
  }
});