// GLOBAL VARIABLES //

// Collect the current user agent
var thisAgent = navigator.userAgent.toLowerCase();
// Detect if the user agent is iPod, iPhone, or iPad
var iPod = (thisAgent.indexOf('ipod') != -1) ? true : false;
var iPhone = (thisAgent.indexOf('iphone') != -1) ? true : false;
var iPad = (thisAgent.indexOf('ipad') != -1) ? true : false;
// Define whether a mobile device is being used
var isMobile = (iPod || iPhone || iPad) ? true : false;

$(document).ready(function(){

  // Fix all TOP links
  $("a[href^=#]").click(function(event){ event.preventDefault(); document.location.hash = $(this).attr('href'); });
  
  // Apply the jFlow to any slides requiring it
  $("#myController").jFlow({
    slides: "#mySlides",
    width: "658px",
    height: "328px",
    duration: 400
  });
  
  // Update all images with "hover" states
  $("img[data-hover]").each(function(){
    // Add a data-blur to the image
    $(this).attr('data-blur', $(this).attr('src'));
    // Add a hover event to the image
    $(this).hover(
      function(){
        $(this).attr('src',$(this).attr('data-hover'));
        },
      function(){
        $(this).attr('src',$(this).attr('data-blur'));
        }
      );
    });
   
  // Add fade-events to all elements with a data-fademe property
  $("*[data-fademe=true]").each(function(){
    $(this).animate({opacity:0.9},100);
    $(this).hover(function(){$(this).animate({opacity:1.0},200);},function(){$(this).animate({opacity:0.9},200);});
    });
    
  // If there is a messagewrapper on the page, clone/move it and add click-events
  if ($("#messagewrapper").length) {
    // Pull the existing messages from the HTML
    var messages = $("#messagewrapper").html();
    // Check to make sure there are messages present
    if (messages.length) {
      // And if so create/initialize the message wrapper
      // with the messages collected above
      create_message_wrapper(messages);
      }
    }
  
  // Active any prettyphoto links
  $("a[rel^='prettyphoto']").prettyPhoto({
    animationSpeed: 'normal', /* fast/slow/normal */
    padding: 40, /* padding for each side of the picture */
    opacity: 0.35, /* Value betwee 0 and 1 */
    showTitle: false, /* true/false */
    allowresize: false, /* true/false */
    counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
    //theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
    hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
    modal: false, /* If set to true, only the close button will close the window */
    allowScrollCentering: false /* If set to true, the image stay centered in the window during scrolling */
    //changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
    //callback: function(){} /* Called when prettyPhoto is closed */
    });
  
  
  // Activate any flow player links
  $("a[data-flowplayer]").each(function(){
    activate_flow_player(this);
    });
  
  // Add click-events to any links with data-videoid
  $("a[data-videoid]").each(function(){
    $(this).click(function(event){
      event.preventDefault();
      _video_id = $(this).attr('data-videoid');
      _video_type = $(this).attr('data-videotype');
      $(this).removeClass('linkBlue').addClass('linkOrange');
      $("a[data-videoid!="+_video_id+"]").removeClass('linkOrange').addClass('linkBlue');
      $.ajax({
        type : 'POST',
        url : 'scripts/get_video_html.php',
        data : 'video_id='+_video_id+'&video_type='+_video_type,
        success : function(html){
          $("#media_frame").html(html);
          activate_flow_player('media_video');
          }
        });
      });
    });
    
  // Add click-events to any links with data-audioid
  $("a[data-audioid]").each(function(){
    $(this).click(function(event){
      event.preventDefault();
      _audio_id = $(this).attr('data-audioid');
      _audio_type = $(this).attr('data-audiotype');
      $(this).removeClass('linkBlue').addClass('linkOrange');
      $("a[data-audioid!="+_audio_id+"]").removeClass('linkOrange').addClass('linkBlue');
      $("#media_frame").animate({opacity:0.0},100);
      $.ajax({
        type : 'POST',
        url : 'scripts/get_audio_html.php',
        data : 'audio_id='+_audio_id+'&audio_type='+_audio_type,
        success : function(html){
          $("#media_frame").html(html);
          $("#media_frame").animate({opacity:1.0},200);
          }
        });
      });
    });
    
  // Add any colorbox events
  plutocms_data_colorbox();
  
});

// --------------------------------- //
// -- COMMON FUNCTIONS ------------- //
// --------------------------------- //

function create_message_wrapper(messages)
{
  var header_object = $("#content-container h1:first");
  if (!header_object.length) { header_object = $("#content-container span:first"); }
  if ($("#messagewrapper").length) { $("#messagewrapper").remove(); }
  header_object.after("<ul id=\"messagewrapper\">"+messages+"</ul>\r\n");
  $("#messagewrapper").css('display', 'block').css('cursor', 'crosshair');
  // Add click-events to all status messages
  $("#messagewrapper li").live("click", function(event){
        event.preventDefault();
        $(this).animate({opacity:0.01,marginTop:"-10px"},300,"linear",function(){
          if ($(this).is("#messagewrapper li:only-child")) {
            $("#messagewrapper").animate({height:"1px"},300).remove();
            }
          else {
            $(this).remove();
            }
          });
        });
}
function new_status_message(colour, message)
{
  // First check to see if the messagewrapper is created
  if (!$("#messagewrapper").length)
  {
    // Create the wrapper if it doesn't exist
    create_message_wrapper('');
  }
  // Now add a message to the wrapper
  $("#messagewrapper").append("<li class=\""+colour+"\">"+message+"</li>");
}
function activate_flow_player(_element_id)
{
  flowplayer(_element_id, "http://www.insightdesign.ca/flash/flowplayer-3.1.4.swf",
      {
      clip:{
        autoPlay: false,
        autoBuffering: true
        },
      canvas:{
        backgroundColor: "#FFFFFF"
        },
      plugins:{
       controls:{
          buttonColor: '#EF9346',
          buttonOverColor: '#FEAA38',
          //durationColor: '#ffffff',
          volumeSliderGradient: 'none',
          //tooltipColor: '#5F747C',
          //tooltipTextColor: '#ffffff',
          progressGradient: 'medium',
          progressColor: '#EF9346',
          volumeSliderColor: '#626262',
          sliderGradient: 'none',
          backgroundColor: '#0171BB',
          backgroundGradient: 'low',
          bufferColor: '#626262',
          timeBgColor: '#626262',
          timeColor: '#D8EEFB',
          borderRadius: '0',
          //bufferGradient: 'none',
          //sliderColor: '#000000',
          height: 24,
          opacity: 1.0
          }
        }
      }
    );
}

// Define a function for processing all data colorbox hooks
function plutocms_data_colorbox(){
  // Change any pretty photo links to lightboxes
  if (jQuery().colorbox){
    $("*[data-colorbox]").each(function(){
      // Prevent the default click action
      $(this).click(function(e){e.preventDefault();});
      // Check if this is an iframe or inline element
      var isIframe = $(this).attr('data-colorbox') == 'iframe' ? true : false;
      var isInline = $(this).attr('data-colorbox') == 'inline' ? true : false;
      // Attempt to collect the HREF from the element
      var thisHref = $(this).attr('href') ? $(this).attr('href') : false;
      // Attempt to collect settings if any are defined
      var customSettings = $(this).attr('data-settings') ? $(this).attr('data-settings') : false;
      // Define the allowable settings editorSettings
      var colorboxSettings = {boxOpacity:'70',boxHref:thisHref,boxClose:'false',boxWidth:(isIframe || isInline ? 600 : false),boxHeight:(isIframe || isInline ? 550 : false)};
      // Attempt to parse the custom settings if present
      plutocms_parse_customsettings(customSettings, colorboxSettings);
      // If the HREF is an actual URL, attach the event
      if (colorboxSettings.boxHref != false){
        // If this is NOT a mobile device
        if (!isMobile){
          // Attach the appropriate colorbox event based on type
          if (isIframe){
            $(this).colorbox({overlayClose:false,opacity:(parseInt(colorboxSettings.boxOpacity)/100),current:'{current} / {total}',href:colorboxSettings.boxHref,iframe:true,innerWidth:colorboxSettings.boxWidth,innerHeight:colorboxSettings.boxHeight,onClosed:(colorboxSettings.boxClose != 'false' ? function(){window.location=colorboxSettings.boxClose+window.location.hash;} : false)});
            } else if(isInline){
            $(this).colorbox({overlayClose:false,opacity:(parseInt(colorboxSettings.boxOpacity)/100),current:'{current} / {total}',href:colorboxSettings.boxHref,inline:true,innerWidth:colorboxSettings.boxWidth,innerHeight:colorboxSettings.boxHeight,onClosed:(colorboxSettings.boxClose != 'false' ? function(){window.location=colorboxSettings.boxClose+window.location.hash;} : false)});
            } else{
            $(this).colorbox({opacity:(parseInt(colorboxSettings.boxOpacity)/100),current:'{current} / {total}',href:colorboxSettings.boxHref,innerWidth:colorboxSettings.boxWidth,innerHeight:colorboxSettings.boxHeight,onClosed:(colorboxSettings.boxClose != 'false' ? function(){window.location=colorboxSettings.boxClose+window.location.hash;} : false)});
            }
          } else {
            $(this).click(function(e){ window.location = colorboxSettings.boxHref; });
          }
        }
      });
    }
}

// Define a function for parsing custom settings out of an HTML attribute
function plutocms_parse_customsettings(customSettings, extensionSettings){
  if (customSettings.length){
    var settingPairs = customSettings.split('|');
    for (var i = 0; i < settingPairs.length; i++){
      var temp = settingPairs[i].match(/([-_a-z0-9]+)=(.*)/i);
      if (!temp){ continue; }
      var thisKey = temp[1] ? temp[1] : false;
      var thisValue = temp[2] ? temp[2] : false;
      if (thisKey == false && thisValue == false){
        continue;
        }else{
        extensionSettings[thisKey] = thisValue;
        }
      }
    }
}

