jQuery(document).ready(function($) {



  /* Film & Videos Page */
  
  var pg = $('div.gys-page-content.film');
  if (pg.size())
  {
    // enable a secondary thickbox link to reuse the constructed link for the video
    $('div.gys-page-content.film div.video a.thickbox-duplicate').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $(this).parents('div.video').find('a.thickbox').click();
    });
  }



  /* Gallery Page (Excl. Galleria, Incl. Order Form) */  
  
  var pg = $('div.gys-page-content.photography-gallery');
  if (pg.size())
  {
    // enable the order print here link to slide out form
    pg.find('a.order-prints-here').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var pg = $('div.gys-page-content.photography-gallery');
      var op = pg.find('div.order-prints');
      op.slideToggle('slow');
    });
    
    // establish a function that we associate with the page
    // which will update the total or display dashes instead
    pg.find('div.form').data('update_total', function(f) {
      
      // initialize flag
      // which tells us when
      // total not applicable      
      var na = false;
      
      // shortcut to the total element
      var t = f.find('div.input.total');
      
      // first extract the quantity as an integer from form
      var qty = parseInt(f.find('input[name=quantity]').val());
      if ((!qty) || (qty < 1)) na = true;
      
      // next extract the unit base price by using
      // the value of drop-down and correlating
      // to the information in the hidden tags
      var ps = f.find('select[name=print_size]');
      if (!ps.val()) na = true;
      else 
      { 
        // extract the base unit price from the proper element as float
        var bp = parseFloat(ps.parent().find('span.amount.'+ps.val()).text());
        if (bp < 0.01) na = true;
      }
      
      // extract the cost of the mount which
      // has been selected or set na flag 
      var mo = f.find('select[name=mount]');
      if (!mo.val()) na = true;
      else var mp = parseFloat(mo.parent().find('span.'+mo.val()).text());
        
      // also determine the cost of postage and
      // take note when no postage is selected
      var st = f.find('select[name=ship_to]');
      if (!st.val()) na = true;
      else var sp = parseFloat(st.parent().find('span.'+st.val()).text());
      
      // when possible 
      // show a total
      if (na)
      {
        // cannot calculate total
        // so just show the dashes
        t.find('.no-total').show();
        t.find('.calculated-total').hide();        
      }
      else
      {
        // we are able to calculate
        // the total so compute the unit
        // price then update total element
        var up = (bp + mp);
        var total = (up * qty) + sp;
        t.find('.calculated-total').text('$'+total.toFixed(2));
        t.find('.calculated-total').show();
        t.find('.no-total').hide();
      }
      
    });
    
    // when either the product of the quantity is altered upate total
    pg.find('div.form select[name=print_size]').change(function(e) {
      var f = $(this).parents('div.form');
      f.data('update_total')(f.parents('form'));
    });
    pg.find('div.form select[name=mount]').change(function(e) {
      var f = $(this).parents('div.form');
      f.data('update_total')(f.parents('form'));
    });
    pg.find('div.form input[name=quantity]').keyup(function(e) {
      var f = $(this).parents('div.form');
      f.data('update_total')(f.parents('form'));
    });
    pg.find('div.form select[name=ship_to]').change(function(e) {
      var f = $(this).parents('div.form');
      f.data('update_total')(f.parents('form'));
    });
    
    // in case the page is display with values update total
    pg.find('div.form').data('update_total')(pg.find('form'));
    
    // when the checkout button is clicked ensure form
    // is valid and show errors when it is not or continue
    pg.find('div.form input.submit').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      
      // locate the form and hide errors
      var f = $(this).parents('form');
      f.find('div.error').hide();
      
      // check to ensure that when a small
      // print is selected a small mount is
      var mo = f.find('select[name=mount]');
      var ps = f.find('select[name=print_size]');
      if (mo.val() != 'mount-none')      
        if ((ps.val() == 'print-small') && (mo.val() != 'mount-small')) f.find('div.error.mount').show();
        else if ((ps.val() != 'print-small') && (mo.val() != 'mount-large')) f.find('div.error.mount').show();
      
      // certain fields only require that a value has been provided so check those
      if (!f.find('input[name=image_code]').val()) f.find('div.error.code').show();
      if (!f.find('select[name=print_size]').val()) f.find('div.error.size').show();      
      if (!f.find('input[name=quantity]').val()) f.find('div.error.quantity').show();
      if (!f.find('select[name=ship_to]').val()) f.find('div.error.ship-to').show();
      if (f.find('div.error:visible').size()) return;
      else
      {
        // retrieve product name and cost
        var ic = f.find('input[name=image_code]').val();
        var ps = f.find('select[name=print_size]');
        var mo = f.find('select[name=mount]');
        var st = f.find('select[name=ship_to]');
        var name = ps.parent().find('span.description.'+ps.val()).text();
        var bp = parseFloat(ps.parent().find('span.amount.'+ps.val()).text());
        var mp = parseFloat(mo.parent().find('span.'+mo.val()).text());
        var sp = parseFloat(st.parent().find('span.'+st.val()).text());
        var up = (bp + mp);
        name = name + ' ('+ic+')';
        
        // prepare the paypal form and submit
        f.find('input[name=item_name]').val(name);
        f.find('input[name=item_number]').val(ic);
        f.find('input[name=amount]').val(up.toFixed(2));
        f.find('input[name=os0]').val((mo.val() != 'mount-none') ? 'Yes' : 'No');
        f.find('input[name=shipping]').val(sp.toFixed(2));
        f.get(0).submit();
      }
    });
    
  }

  
  
  /* Lightbox'd Contact Form */
  
  // since the javascript for the contact cannot be applied until
  // the contact form is present store the function in the footer
  $('#gys-stylized-name-footer').data('contact_ready', function() {
    var $ = jQuery;
    
    // establish the functionality necessary to send the message
    $('#gys-contact-form form div.send-link a').click(function(e) {
      var f = $('#gys-contact-form form');
      
      // create reference to all
      // elements for easy hiding
      var df = f.find('div.form');
      var aj = f.find('div.ajax');
      aj.hide();
      df.hide();
      
      // the first task in our attempt to 
      // send the message is to show activity
      var ajp = f.find('div.ajax.processing');
      ajp.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();
        
        // determine if any error was reported by the
        // server or if we could not connect to server
        if ((!data.success) || (status != 'success'))
        {
          var aje = f.find('div.ajax.error');
          aje.find('span.message').text(data.error);
          aj.hide();
          aje.show();
        }
        else
        {
          // we were successul so show element
          var ajs = f.find('div.ajax.success');
          aj.hide();
          ajs.show();
        }
      };
      
      // compose an execute the ajax request
      $.ajax({ url: 'contact_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 return to form link to hide ajax elements and show
    $('#gys-contact-form form a.return-to-form').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var f = $('#gys-contact-form form');
      f.find('div.ajax').hide();
      f.find('div.form').show();
    });    
  });
  
});

//////////////////////////////////////
// BEGIN GALLERIA RELATED FUNCTIONS //
//////////////////////////////////////

// slide show global variables
var gys__slideshowHandler = null;
var gys__slideshowDelay = 5; // seconds

function gys__slideshowPlay()
{
  // this advances the
  // gallery at intervals
  jQuery.galleria.next();
  gys__slideshowHandler = setTimeout('gys__slideshowPlay()', gys__slideshowDelay * 1000);
}

jQuery(function($) { 
  
  $('ul.galleria-gallery').galleria({
  	history   : false, // deactivates the history object for bookmarking, back-button etc.
  	clickNext : true, // helper for making the image clickable
  	insert    : '#gys-galleria-feature', // the containing selector for our main image
  	
  	onImage   : function(image, caption, thumb) { // let's add some image effects for demonstration purposes
  			
  		// fetch the thumbnail container
  		var _li = thumb.parents('li');
  		
  		// fade out inactive thumbnail
  		_li.siblings().find('img.selected').fadeTo(500,0.4);
  		
  		// fade in active thumbnail
  		thumb.fadeTo('fast',1).addClass('selected');
  		
  		// add a title for the clickable image
  		image.attr('title','Next image >>');
  		
  		// ensure the image is not wider than box
  		// use the styled width for the container
  		var _div = image.parents('div.feature'); 
  		var _width = parseInt(_div.css('width').replace(/px/, ''));
  		if (image.width() > _width) image.css({width: _width});
  		
  		// ensure the image is not taller than wrapper
  		// use the styled width for the image container
  		var _div = image.parents('div.galleria_wrapper'); 
  		var _height = parseInt(_div.css('height').replace(/px/, ''));
  		if (image.height() > _height) image.css({height: _height});
  		
  		// now center the image within the available height
  		//image.css({marginTop: -(image.height() - _height)/2});  									
  	},
  	
  	onThumb : function(thumb) { // thumbnail effects goes here
  		
  		// fetch the thumbnail container
  		var _li = thumb.parents('li');
  		
  		// if thumbnail is active, fade all the way.
  		var _fadeTo = _li.is('.active') ? '1' : '0.3';
  		
  		// fade in the thumbnail when finnished loading
  		thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
  		
  		// hover effects
  		thumb.hover(
  			function() { thumb.fadeTo('fast',1); },
  			function() { _li.not('.active').find('img').fadeTo('fast',0.4); } // don't fade out if the parent is active
  		)
  	}
  });

});

jQuery(document).ready(function($){

  // add the proper actions to the next and previous links
  $('#gys-galleria-navigation a.previous').click(function(e) {
    e.preventDefault();
    $.galleria.prev();
  });
  $('#gys-galleria-navigation a.next').click(function(e) {
    e.preventDefault();
    $.galleria.next();
  });
  
  // add the slide show controls functionality to the play link
  $('div#gys-galleria-navigation div.left a').click(function(e) {
    var el = $(this).blur();
    e.preventDefault();
    
    // determine if slideshow
    // is underway and take action
    if (el.hasClass('playing'))
    { 
      el.text('play slideshow'); 
      el.removeClass('playing');
      clearTimeout(gys__slideshowHandler);
    }
    else 
    { 
      el.text('pause slideshow'); 
      el.addClass('playing');
      gys__slideshowPlay();
    }
  });
       
});

////////////////////////////////////
// END GALLERIA RELATED FUNCTIONS //
////////////////////////////////////

  
