/* Author: Brad Richardson */

// Anomymous Function for cleaner javascript
(function ($) {
  
  // Extensions
  
  // Form Input Focus
  $.fn.extend({
    focusValue: function() {
      return this.each(function() {
        var _switch = function() {
          if($(this).val() == '' || $(this).val() == $(this).data('initial_value')) {
            var val = $(this).val() == '' ? $(this).data('initial_value') : '';
            $(this).val(val);
          }
        };
        $(this).data('initial_value', $(this).val());
        $(this).focus(_switch).blur(_switch);
      });
    }
  });

  // JQuery Scripting
  $(document).ready(function () {
  
    // Show the page
    $('#x1-wrapper').fadeIn(300);
    $('#x1-wrapper-sub').fadeIn(300);
    $('#x2-wrapper').fadeIn(300);
    $('#x2-wrapper-sub').fadeIn(300);
    $('#x3-wrapper').fadeIn(300);
    $('#x4-wrapper').fadeIn(300);
    

    // Browser Reject
    $.reject();
    
    
    // Set browser smooth scroll sections
    $('.backtotop').localScroll();
    
    
    // Image Crossfade
    $("img.a").hover(function () {
      $(this).stop().animate({ "opacity": "0" }, 100);
    }, function () {
      $(this).stop().animate({ "opacity": "1" }, 600);
    });


    // Form Button Click
    $('.headersearch-button').click(function (e) {
      var search = $('.headersearch');
      if (search.val() == search.data('initial_value') || search.val() == '' || search.val() == NaN) {
        e.preventDefault();
        alert('Please provide a valid search phrase.');
        return false;
      }
    });
    
    
    // Form Remove / Add Input Value
    $('input[type=text]').focusValue();
    
    
    // Quicklaunch
    $('.quicklaunch-button').click(function(e) {
      var selectValue = $(this).parent('.header-quicklaunch-elementbody-right').parent('.header-quicklaunch-elementbody').find('.header-quicklaunch-elementbody-left').find('.quicklaunch').val();
      if (selectValue == '-1') {
        e.preventDefault();
        alert('Please select a proper destination.');
        return false;
      }
      else {
        document.location = selectValue;
      }
    });
    
    
    // Home Header Image Flipper
    // Set the width of the image bar's contents
    var wordsWidth = $('.header-imagebar-left').outerWidth();
    var buttonWidth = $('.header-imagebar-right').width();
    var totalWidth = wordsWidth + buttonWidth;
    $('.header-imagebar-container').css('width', totalWidth);
    
    // Find the total number of images
    var totalNum = $('.header-image');
    
    // Set increment, start at 2 due to the first element already being shown
    var num = 2;
    
    // Set the parent container of the flipper
    var flipperContainer = $('.header-top-left');
    
    // Set a boolean variable for active or not
    var flipperActive = false;
    
    // Create the run function
  var runFlipper = function () {

    if (!flipperActive) {

      flipperActive = true;

      flipperContainer.everyTime(6000, 'flipper', function() {

        var currentFlip = ".n" + num;

        $('.header-image').hide().filter(currentFlip).fadeIn(300);
        $('.header-imagebar').hide().filter(currentFlip).fadeIn(300);

        if (num == totalNum.length) {
          num = 1;
        }
        else {
          num++;
        }

      });

    }

  };
  
  // Run the flipper
  runFlipper();

  // Create the stop function
  var stopFlipper = function () {
    flipperContainer.stopTime('flipper');
    flipperActive = false;
  };

  // Set the click function of each button * Not needed

  // Set the hover function of the content bar
  $('.header-imagebar').hover(function () {
    // Stop the flipper
    stopFlipper();
  }, function () {
    // Restart the flipper
    runFlipper();
  });


  // Sub Logo Bubble
  $('.header-logo').hover(function () {
    $('.header-logo-bubble').fadeToggle(300);
  });


  // Translation hover
  $('.flag').click(function () {
    $('.flag-popup').fadeToggle(300);
  });

  $('.flag-popup-element').hover(function () {
    $(this).addClass('selected');
  }, function () {
    $(this).removeClass('selected');
  });


  // Mobile Navigation Show
  $('#seenav').click(function () {
    $('#navigation').slideToggle(300);
  });


  // Membership Contact form Emails
  var currentSelect = $('.personthatyouwouldliketocontact .form-element-sub').find('select');
  var emailTo = $('.emailto .form-element-sub span').find('input[type=hidden]');
  currentSelect.html('');
  $('<option value="fnixon@safefed.org">-- Please select form recipient --</option><option value="mbaibak@safefed.org">Columbia, Irmo and Lexington areas - Mandy Baibak</option><option value="fnixon@safefed.org">All other areas - Faye Nixon</option>').appendTo(currentSelect);
  $(currentSelect).change(function() {
    //$(emailTo).val($('.personthatyouwouldliketocontact .form-element-sub select option:selected').val());
    var selVal = $('.personthatyouwouldliketocontact .form-element-sub select option:selected').val();
    $(emailTo).val(selVal);
  });


  // Email a Friend Link
  var pageLink = window.location.protocol + '//' + window.location.host + $.query.get('page');
  $('.contourField.url').find('input[type=hidden]').val(pageLink);
  
  
  // Show chat balloon
  var viewportWidth = $(window).width();
  if (viewportWidth < 1192) {
    
    $('.chat-balloon').addClass('chat-balloon-other');
    $('.chat-content').addClass('chat-content-other')
    
    $('.chathover').hover(function() {
      $('.chat-balloon').fadeIn(300);
    }, function() {
      $('.chat-balloon').fadeOut(200);
    });
    
  }
  else {
    
    $('.chathover').hover(function() {
      $('.chat-balloon').fadeIn(300);
    }, function() {
      $('.chat-balloon').fadeOut(200);
    });
    
  }

  });

})(window.jQuery);


// Printer Friendly Version
var gAutoPrint = true; // Tells whether to automatically call the print function

function printSpecial() {
    if (document.getElementById != null) {
        var html = '<HTML>\n<HEAD>\n';

        if (document.getElementsByTagName != null) {
            //var headTags = document.getElementsByTagName("head");
            //if (headTags.length > 0)
            //html += headTags[0].innerHTML;
        }

        html += '\n<link rel="stylesheet" type="text/css" href="/css/style.css" />\n';
        html += '\n<link rel="stylesheet" type="text/css" href="/css/element.css" />\n';
        html += '\n<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>\n';
        html += '\n<script type="text/javascript" src="/scripts/mylibs/GoogleMapping.js"></script>\n';
        html += '\n</HEAD>\n<BODY style="background-color: #ffffff; padding: 20px;"  onload="OnLoad()" onresize="OnLoad()">\n';

        var printReadyElem = document.getElementById("printReady");

        if (printReadyElem != null) {
            html += '\n<div class="print-content-container">\n'
            html += printReadyElem.innerHTML;
        }
        else {
            alert("Could not find the printReady function");
            return;
        }

        var printReadyElem2 = document.getElementById("printerfriendlycontent");

        if (printReadyElem2 != null) {
            html += printReadyElem2.innerHTML;
            html += '\n<div class="form-sub container"><p><br /><br />All rights reserved. Copyright 2011 - 2012</p></div>\n';
            html += '\n</div>\n';
        }
        else {
            html += '\n</div>\n';
        }

        html += '\n</BODY>\n</HTML>';

        var printWin = window.open("", "printSpecial");
        printWin.document.open();
        printWin.document.write(html);
        printWin.document.close();
        if (gAutoPrint)
            printWin.print();
    }
    else {
        alert("The print ready feature is only available if you are using a browser. Please update your browser.");
    }
}


// Newsletter Manager Pro Sign Up Validation
function $Npro(field) {
  var element =  document.getElementById(field);
  return element;
  return false;
}
function emailvalidation(field, errorMessage) {
  var goodEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\..{2,2}))$)\b/gi);
  apos = field.value.indexOf("@");
  dotpos = field.value.lastIndexOf(".");
  lastpos = field.value.length - 1;
  var badEmail = (apos<1 || dotpos-apos<2 || lastpos-dotpos<2)
  if (goodEmail && !badEmail) { return true; }
  else {
    alert(errorMessage);
    //$Npro("Error").innerHTML = errorMessage;
    //$Npro("Error").style.display = "inline";
    field.focus();
    field.select();
    return false;
  }
}
function emptyvalidation(entered, errorMessage) {
    $Npro("Error").innerHTML = "";
    with (entered) {
      if (value==null || value=="") {
          alert(errorMessage);
          //$Npro("Error").innerHTML = errorMessage;
          //$Npro("Error").style.display = "inline";
          return false;
    }
      else { return true; }
  }
}
function formvalidation(thisform) {
  with (thisform) {
    if (emptyvalidation(name,"Please enter your name") == false) { 
      name.focus();
      return false;
    };
    if (emptyvalidation(lastname,"Please enter your last name") == false) {
      lastname.focus();
      return false;
    };
    if (emailvalidation(email,"Please enter your valid email address") == false) {
      email.focus();
      return false;
    };
  }
}


// Highslide Configuration
hs.graphicsDir = '/highslide/graphics/';
hs.showCredits = false;
hs.outlineType = 'custom';
hs.dimmingOpacity = 0.7;
hs.captionEval = 'this.a.title';
hs.registerOverlay({
  html: '<div class="closebutton" onclick="return hs.close(this)" title="Close"></div>',
  position: 'top right',
  useOnHtml: true,
  fade: 2 // fading the semi-transparent overlay looks bad in IE
});


// LiveChat Configuation
var __lc_buttons = __lc_buttons || [];
__lc_buttons.push({
  elementId: 'LiveChat_1315836553',
  language: 'en',
  skill: '0'
});
