/****************************************************/
/* Kuranda Roots Festival -- Javascript (All Pages) */
/****************************************************/

jQuery(document).ready(function($) {
  
  /*********************/
  /* Image Pre-Loading */
  /*********************/
  
  // establish reusable
  // preloading method
  (function($){
    $('body').data('preloader', new Array());
    $('body').data('preload', function(src) {
      var arr = $('body').data('preloader');
      var img = new Image();
      img.src = src;
      arr[arr.length] = img;
    });
  })(jQuery);
  
  // use following to preload images start with other backgrounds
  $('body').data('preload')('pics/bg__brown_brushed_opaque.jpg');
  
  /**************/
  /* Navigation */
  /**************/
  
  // define a function which will
  // encapsulate our ajax navigation
  var navigate = function(pg) {
    var b = $('#krts-body');    
    plb__lightbox.close();
    b.removeClass().addClass(pg);
  };
  
  $('.krts-goto-home').click(function(e) { e.preventDefault(); navigate('home'); $(this).blur(); });
  $('.krts-goto-line-up').click(function(e) { 
    e.preventDefault();
    navigate('home');
    
    // after navigating to the home page jump to the line up
    $(window).scrollTop($('#krts-artist-bios').position().top);
  });
  $('.krts-goto-about').click(function(e) { 
    e.preventDefault();
    
    // reset the slideshow whenever we navigate to the about page
    var el = $('div#krts-content-area div.content.about div.slideshow');
    el.data('reset_slides')(el);
    navigate('about'); 
    $(this).blur(); 
  });
  $('.krts-goto-program').click(function(e) { e.preventDefault(); navigate('program'); $(this).blur(); });
  $('.krts-goto-tickets').click(function(e) { e.preventDefault(); navigate('tickets'); $(this).blur(); });
  $('.krts-goto-contact').click(function(e) { e.preventDefault(); navigate('contact'); $(this).blur(); });
  
  /*********************/
  /* Poster Slide Show */
  /*********************/
  
  var d = $('div#krts-poster-slideshow');
  if (d.size())
  {
    // for compatibility 
    // with reused code
    var el = d;
    
    // time to wait between transitions and duration of each animation
    el.data('delay', parseFloat(el.find('span.krts-slideshow-delay').text())); // seconds
    el.data('transition', parseFloat(el.find('span.krts-slideshow-transition').text())); // seconds
    if (!el.data('delay') || el.data('delay') < 0.5) el.data('delay', 1);
    if (!el.data('transition') || el.data('transition') < 0.5) el.data('transition', 0.5);
    
    // esetablish the array of slides in the show container
    el.data('slides', el.find('div.slides div.slide').get());
    el.data('current', 0);
    el.data('preloader', new Array());
    
    // determine the current slide by locating the first visible slide within the array and saving the offset
    for (var j=0; j<el.data('slides').length; j++) if (!($(el.data('slides')[j]).hasClass('rkat-hidden'))) el.data('current', j);
    for (var j=0; j<el.data('slides').length; j++) { el.data('preloader')[j] = new Image(); el.data('preloader')[j].src = $(el.data('slides')[j]).find('img').attr('src'); }
    
    // associate a rotation function with the
    // feature requiring itself as parameter
    el.data('rotate_slides', function(el) {
      
      // when no slides present abort rotations
      if (el.data('slides').length < 1) return;
      
      // determine the next index using a modulus operator
      el.data('next', ((el.data('current') + 1) % el.data('slides').length));
      var c = $(el.data('slides')[el.data('current')]);
      var n = $(el.data('slides')[el.data('next')]);
      
      // stop animation if there is only one slide in show
      if (el.data('next') == el.data('current')) return;
      
      // begin animation of current and next
      c.fadeOut(el.data('transition')*1000);
      n.fadeIn(el.data('transition')*1000);
      
      // update our current offset
      el.data('current', el.data('next'));
      
      // ensure that the next slide
      // is visible when it fades in
      n.removeClass('krts-hidden');
      
      // schedule the next rotation of the slide show images using absolute references to show
      el.data('handler', setTimeout("jQuery('div#krts-poster-slideshow').data('rotate_slides')("+
                                    "jQuery('div#krts-poster-slideshow')"+")", el.data('delay') * 1000));      
    });
    
    // additionally associate reset routine
    el.data('reset_slides', function(el) {
      
      // clear any scheduled transition
      // stop animations and reset opacity
      clearTimeout(el.data('handler'));
      for (var i=0; i<el.data('slides').length; i++) $(el.data('slides')[i]).stop();
      for (var i=0; i<el.data('slides').length; i++) $(el.data('slides')[i]).css('opacity', 1);
      
      // set the current to 
      // the first then show
      // and hide all others
      el.data('current', 0);
      $(el.data('slides')[el.data('current')]).show();
      for (var i=1; i<el.data('slides').length; i++) $(el.data('slides')[i]).hide();
      
      // reschedule the rotation after the proper delay saving the handler in case of reset
      el.data('handler', setTimeout("jQuery('div#krts-poster-slideshow').data('rotate_slides')("+
                                    "jQuery('div#krts-poster-slideshow')"+")", el.data('delay') * 1000));      
    });

    // schedule the first rotation of the slide show images using absolute references to show
    el.data('handler', setTimeout("jQuery('div#krts-poster-slideshow').data('rotate_slides')("+
                                  "jQuery('div#krts-poster-slideshow')"+")", el.data('delay') * 1000));
  }
  
  /*************************/
  /* Wood Board Slide Show */
  /*************************/
  
  var d = $('div#krts-wood-board-slideshow');
  if (d.size())
  {
    // for compatibility 
    // with reused code
    var el = d;
    
    // time to wait between transitions and duration of each animation
    el.data('delay', parseFloat(el.find('span.krts-slideshow-delay').text())); // seconds
    el.data('transition', parseFloat(el.find('span.krts-slideshow-transition').text())); // seconds
    if (!el.data('delay') || el.data('delay') < 0.5) el.data('delay', 1);
    if (!el.data('transition') || el.data('transition') < 0.5) el.data('transition', 0.5);
    
    // esetablish the array of slides in the show container
    el.data('slides', el.find('div.slides div.slide').get());
    el.data('current', 0);
    el.data('preloader', new Array());
    
    // determine the current slide by locating the first visible slide within the array and saving the offset
    for (var j=0; j<el.data('slides').length; j++) if (!($(el.data('slides')[j]).hasClass('rkat-hidden'))) el.data('current', j);
    for (var j=0; j<el.data('slides').length; j++) { el.data('preloader')[j] = new Image(); el.data('preloader')[j].src = $(el.data('slides')[j]).find('img').attr('src'); }
    
    // associate a rotation function with the
    // feature requiring itself as parameter
    el.data('rotate_slides', function(el) {
      
      // when no slides present abort rotations
      if (el.data('slides').length < 1) return;
      
      // determine the next index using a modulus operator
      el.data('next', ((el.data('current') + 1) % el.data('slides').length));
      var c = $(el.data('slides')[el.data('current')]);
      var n = $(el.data('slides')[el.data('next')]);
      
      // stop animation if there is only one slide in show
      if (el.data('next') == el.data('current')) return;
      
      // begin animation of current and next
      c.fadeOut(el.data('transition')*1000);
      n.fadeIn(el.data('transition')*1000);
      
      // update our current offset
      el.data('current', el.data('next'));
      
      // ensure that the next slide
      // is visible when it fades in
      n.removeClass('krts-hidden');
      
      // schedule the next rotation of the slide show images using absolute references to show
      el.data('handler', setTimeout("jQuery('div#krts-wood-board-slideshow').data('rotate_slides')("+
                                    "jQuery('div#krts-wood-board-slideshow')"+")", el.data('delay') * 1000));      
    });
    
    // additionally associate reset routine
    el.data('reset_slides', function(el) {
      
      // clear any scheduled transition
      // stop animations and reset opacity
      clearTimeout(el.data('handler'));
      for (var i=0; i<el.data('slides').length; i++) $(el.data('slides')[i]).stop();
      for (var i=0; i<el.data('slides').length; i++) $(el.data('slides')[i]).css('opacity', 1);
      
      // set the current to 
      // the first then show
      // and hide all others
      el.data('current', 0);
      $(el.data('slides')[el.data('current')]).show();
      for (var i=1; i<el.data('slides').length; i++) $(el.data('slides')[i]).hide();
      
      // reschedule the rotation after the proper delay saving the handler in case of reset
      el.data('handler', setTimeout("jQuery('div#krts-wood-board-slideshow').data('rotate_slides')("+
                                    "jQuery('div#krts-wood-board-slideshow')"+")", el.data('delay') * 1000));      
    });

    // schedule the first rotation of the slide show images using absolute references to show
    el.data('handler', setTimeout("jQuery('div#krts-wood-board-slideshow').data('rotate_slides')("+
                                  "jQuery('div#krts-wood-board-slideshow')"+")", el.data('delay') * 1000));
  }
  
  /**************/
  /* News Panel */
  /**************/
  
  var np = $('div#krts-news-panel');
  if (np.size())
  {
    // as soon as document is ready preload the control images
    $('body').data('preload')('pics/itm__news_arrow_up_enabled.png');
    $('body').data('preload')('pics/itm__news_arrow_up_disabled.png');
    $('body').data('preload')('pics/itm__news_arrow_down_enabled.png');
    $('body').data('preload')('pics/itm__news_arrow_down_disabled.png');
    
    // the article previews element holds
    // and limits the height of the movable
    var mc = np.find('.movable-container');
    var ap = np.find('.article-previews');
    var up = np.find('.scrolling-controls .up');
    var down = np.find('.scrolling-controls .down');
    if (mc.height() > ap.height()) down.removeClass('disabled');
    
    // associate a function to update the states
    // of the news panel scrolling controls here
    mc.data('refresh-controls', function() {
      var mc = $('div#krts-news-panel div.movable-container');
      var ap = mc.parent();
      var controls = ap.parents('div#krts-news-panel').find('.scrolling-controls');
      var up = controls.find('.up');
      var down = controls.find('.down');
      var top = mc.position().top;
      if (top >= 0) up.addClass('disabled'); else up.removeClass('disabled');
      if (top <= (-mc.height() + ap.height())) down.addClass('disabled'); else down.removeClass('disabled');
    });
    
    // enable the scrolling
    // controls to operate
    up.click(function(e) {
      var mc = $(this).parents('div#krts-news-panel').find('.movable-container');
      var ap = mc.parent();
      var top = mc.position().top;
      top = top + (ap.height() / 2);
      if (top > 0) top = 0;
      mc.animate({ top: (top+'px') }, 1000, 'swing', mc.data('refresh-controls'));
    });
    down.click(function(e) {
      var mc = $(this).parents('div#krts-news-panel').find('.movable-container');
      var ap = mc.parent();
      var top = mc.position().top;
      top = top - (ap.height() / 2);
      var min = -mc.height() + ap.height();
      if (top < min) top = min;
      mc.animate({ top: (top+'px') }, 1000, 'swing', mc.data('refresh-controls'));
    });
    
    // now allow the article preview titles and the properly styled more links to open full text
    np.find('div.article-preview h3 a, div.article-preview div.preview span.more a').click(function(e) {
      e.preventDefault();
      var ap = $(this).parents('div.article-preview');
      var article_id = parseInt(ap.find('span.article_id').text());
      if (article_id < 1) return;
      
      // show the activity indicator while we make the ajax request to retrieve the full article content 
      plb__lightbox.open($('#krts-embedded-lightbox-loading-graphic .krts-lightbox-loading-graphic').clone(), true);
      
      // define a function which will handle
      // both success and failure of our post
      var complete = function(data, status) { 
        var html = '';
        
        // determine if any system error was reported by the process of checking request and response data
        if ((!data) || (status != 'success')) html = '<span>System/Network Error.  Please try again.</span>';
        else html = data;
          
        // open the lightbox content
        plb__lightbox.open($(html));
      };
      
      // compose and execute the ajax request to get the article
      $.ajax({ url: 'full_articles.php?article_id='+article_id,
               type: 'POST',
               cache: false,               
               dataType: 'html',
               success: complete,
               error: complete });
    });
  }
  
  /**************/
  /* About Page */
  /**************/
  
  var d = $('div#krts-content-area div.content.about');
  if (d.size())
  {
    // prepare the photo slide show
    var el = d.find('div.slideshow');
    
    // time to wait between transitions
    // and duration of each animation
    el.data('delay', 2); // seconds
    el.data('transition', 0.5); // seconds
    
    // esetablish the array of slides in the element
    el.data('slides', el.find('div.slides img').get());
    el.data('current', 0);
    el.data('preloader', new Array());
    
    // determine the current slide by locating the first visible slide within the array and saving the offset
    for (var j=0; j<el.data('slides').length; j++) if (!($(el.data('slides')[j]).hasClass('rkat-hidden'))) el.data('current', j);
    for (var j=0; j<el.data('slides').length; j++) { el.data('preloader')[j] = new Image(); el.data('preloader')[j].src = $(el.data('slides')[j]).attr('src'); }
    
    // associate a rotation function with the
    // feature requiring itself as parameter
    el.data('rotate_slides', function(el) {
      
      // when no slides present abort rotations
      if (el.data('slides').length < 1) return;
      
      // determine the next index using a modulus operator
      el.data('next', ((el.data('current') + 1) % el.data('slides').length));
      var c = $(el.data('slides')[el.data('current')]);
      var n = $(el.data('slides')[el.data('next')]);
      
      // stop animation if there is only one slide in show
      if (el.data('next') == el.data('current')) return;
      
      // begin animation of current and next
      c.fadeOut(el.data('transition')*1000);
      n.fadeIn(el.data('transition')*1000);
      
      // update our current offset
      el.data('current', el.data('next'));
      
      // ensure that the next slide
      // is visible when it fades in
      n.removeClass('krts-hidden');
      
      // schedule the next rotation of the slide show images used absolute references to slide show element
      el.data('handler', setTimeout("jQuery('div#krts-content-area div.content.about div.slideshow').data('rotate_slides')("+
                                    "jQuery('div#krts-content-area div.content.about div.slideshow')"+")", el.data('delay') * 1000));      
    });
    
    // additionally associate reset routine
    el.data('reset_slides', function(el) {
      
      // clear any scheduled transition
      // stop animations and reset opacity
      clearTimeout(el.data('handler'));
      for (var i=0; i<el.data('slides').length; i++) $(el.data('slides')[i]).stop();
      for (var i=0; i<el.data('slides').length; i++) $(el.data('slides')[i]).css('opacity', 1);
      
      // set the current to 
      // the first then show
      // and hide all others
      el.data('current', 0);
      $(el.data('slides')[el.data('current')]).show();
      for (var i=1; i<el.data('slides').length; i++) $(el.data('slides')[i]).hide();
      
      // reschedule the rotation after the proper delay saving the handler in case of reset
      el.data('handler', setTimeout("jQuery('div#krts-content-area div.content.about div.slideshow').data('rotate_slides')("+
                                    "jQuery('div#krts-content-area div.content.about div.slideshow')"+")", el.data('delay') * 1000));      
    });

    // schedule the first rotation of the slide show images used absolute references to slide show element
    el.data('handler', setTimeout("jQuery('div#krts-content-area div.content.about div.slideshow').data('rotate_slides')("+
                                  "jQuery('div#krts-content-area div.content.about div.slideshow')"+")", el.data('delay') * 1000));
  }
  
  /****************/
  /* Contact Page */
  /****************/
  
  // all functionality to the contact form elements including focus
  var d = $('div#krts-content-area div.content.contact div.form');
  if (d.size())
  {
    // add functionality which darkens the text on
    // focus and removes the embedded labels too
    d.find('input, textarea').focus(function(e) {
      var el = $(this);
      if (el.attr('name') == 'name' && el.val() == 'NAME') { el.addClass('focused'); el.val('');}
      if (el.attr('name') == 'email' && el.val() == 'EMAIL') { el.addClass('focused'); el.val('');}
      if (el.attr('name') == 'message' && el.val() == 'MESSAGE') { el.addClass('focused'); el.val(''); }
    });
    d.find('input, textarea').blur(function(e) {
      var el = $(this);
      if (el.attr('name') == 'name' && el.val() == '') { el.removeClass('focused'); el.val('NAME'); }
      if (el.attr('name') == 'email' && el.val() == '') { el.removeClass('focused'); el.val('EMAIL');  }
      if (el.attr('name') == 'message' && el.val() == '') { el.removeClass('focused'); el.val('MESSAGE');  }
    });
    
    // when send button is clicked execute
    d.find('div.button a').click(function(e) {
      e.preventDefault();
      var f = $(this).parents('div.form');
      
      // the first task in our attempt to 
      // send the message is to show status
      var ajs = f.find('div.ajax-status');
      ajs.find('.loading-indicator').show();
      ajs.find('.results').hide();
      ajs.find('.close').hide();
      ajs.show();
      
      // define a function which will handle
      // both success and failure of our post
      var complete = function(data, status) { 
        if (!(data instanceof Object)) data = new Object();
        var msg = null;
        ajs.find('.results span').hide();
        ajs.find('.results .error').html('');
        
        // determine if any error was reported by the
        // process of checking request and response data
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'Error; Please try again.';
          ajs.find('.results .error').html(error);
          ajs.find('.results .error').show();
        }
        else ajs.find('.results .success').show();
        
        // after message is determined show
        ajs.find('.loading-indicator').hide();
        ajs.find('.results').show();
        ajs.find('.close').show();
      };
      
      // compose and execute the ajax request
      $.ajax({ url: 'contact_form_processor.php',
               type: 'POST',
               cache: false,               
               data: { name: f.find('input[name=name]').val(),
                       email: f.find('input[name=email]').val(),
                       message: f.find('textarea[name=message]').val()                       
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    });
    
    // enable the close link on the window to function
    d.find('div.ajax-status .close a').click(function(e) {
      e.preventDefault();
      var ajs = $(this).parents('div.ajax-status');
      if (ajs.find('.results .error:visible').size()) { ajs.hide(); return; }
      ajs.hide();
      var f = ajs.parents('div.form');
      f.find('input[name=name]').val('');
      f.find('input[name=email]').val('');
      f.find('textarea[name=message]').val('');
      f.find('input, textarea').blur();
    });
  }
  
  /*************************/
  /* Lightbox'd Directions */
  /*************************/
  
  $('.krts-lightboxed-directions-opener').click(function(e) {
    e.preventDefault();
    
    // simply open the embedded content using the lightbox opening routine on a copy
    plb__lightbox.open($('#krts-embedded-directions .krts-directions-lightbox').clone());    
  });
  
  /*****************************/
  /* Lightbox'd Poster (Image) */
  /*****************************/
  
  $('.krts-lightboxed-poster-opener').click(function(e) {
    e.preventDefault();
    
    // which poster to open in stored with the link
    var index = $(this).find('span.index').text();
    if (!index) return;
    
    // when the program image has been requested begin by showing the lightbox loading image and locking the view
    plb__lightbox.open($('#krts-embedded-lightbox-loading-graphic .krts-lightbox-loading-graphic').clone(), true);
    
    // now locate the image holder with the proper index on the page and retrieve the source of the image
    var ih = $('#krts-embedded-poster-image-holder-lightbox.index-'+index+' .krts-image-holder-lightbox');
    var src = ih.find('img.poster').attr('src');
    
    // begin the preloading
    // sequence for image
    var img = new Image();
    img.onload = function(){
      img.onload = null;
      
      // after image has loaded determine
      // the available space in the window
      var maxh = $(window).height() - 40;
      
      // prepare a clone of 
      // the image holder
      var cl = ih.clone();
      if (maxh < img.height)
      {
        // when the image is too
        // big add scrolling
        cl.css('height', maxh);
        cl.css('width', img.width + 18);
      }
      else
      {
        // otherwise just show the image
        cl.css('height', img.height);
        cl.css('width', img.width);
      }
      
      // open with lightbox
      plb__lightbox.open(cl);
    };
    
    // set the source
    // and load image
    img.src = src;
  });

  /******************************/
  /* Lightbox'd Program (Image) */
  /******************************/
  
  $('.krts-lightboxed-program-opener').click(function(e) {
    e.preventDefault();
    
    // when the program image has been requested begin by showing the lightbox loading image and locking the view
    plb__lightbox.open($('#krts-embedded-lightbox-loading-graphic .krts-lightbox-loading-graphic').clone(), true);
    
    // now locate the image holder on the page and retrieve the source of the image file
    var ih = $('#krts-embedded-program-image-holder-lightbox .krts-image-holder-lightbox');
    var src = ih.find('img.program').attr('src');
    
    // begin the preloading
    // sequence for image
    var img = new Image();
    img.src = src;
    img.onload = function(){
      img.onload = null;
      
      // after image has loaded determine
      // the available space in the window
      var maxh = $(window).height() - 40;
      
      // prepare a clone of 
      // the image holder
      var cl = ih.clone();
      if (maxh < img.height)
      {
        // when the image is too
        // big add scrolling
        cl.css('height', maxh);
        cl.css('width', img.width + 18);
      }
      else
      {
        // otherwise just show the image
        cl.css('height', img.height);
        cl.css('width', img.width);
      }
      
      // open with lightbox
      plb__lightbox.open(cl);
    };
  });
  
  /********************/
  /* Lightbox'd Terms */
  /********************/
  
  var d = $('div#krts-footer');
  if (d.size())
  {
    // simply associate each of the footer links with the proper lightbox opening action using the content that is already emebedded on the page
    d.find('a.festival-terms').click(function(e) { e.preventDefault(); plb__lightbox.open($('#krts-embedded-festival-terms .krts-terms-lightbox').clone()); });
    d.find('a.terms-of-use').click(function(e) { e.preventDefault(); plb__lightbox.open($('#krts-embedded-terms-of-use .krts-terms-lightbox').clone()); });
  }
  
  /****************************/
  /* Lightbox'd Bus Timetable */
  /****************************/
  
  $('.krts-lightboxed-bus-timetable-opener').click(function(e) {
    e.preventDefault();
    
    // simply open the embedded content using the lightbox opening routine on a copy
    plb__lightbox.open($('#krts-embedded-bus-timetable .krts-terms-lightbox').clone());    
  });
  
  /**********************************************/
  /* Lightbox'd Festival Wrap-Up (Auto-Loading) */
  /**********************************************/
  
  var d = $('#krts-embedded-festival-wrap-up');
  if (d.size() && d.hasClass('activated'))
  {
    // when properly activate with css class open immediately
    plb__lightbox.open(d.find('.krts-terms-lightbox').clone());
  }
  
});
