var menuTimeout = 500;
var slideTime = 100;
var closeMenuTimer = 0;
var openMenuItem = 0;
var openSubmenuItem = 0;
var openSubsubmenuItem = 0;

function closeMenus()
{
  //if (openMenuItem) openMenuItem.hide();
  $('.menudrop').hide();
  $('.topsubmenu').hide();
  closeSubMenu();
}

function closeSubMenu()
{
  //if (openSubmenuItem) openSubmenuItem.hide();
  $('.submenudrop').hide();
  closeSubsubMenu();
}

function closeSubsubMenu()
{
  if (openSubsubmenuItem) openSubsubmenuItem.hide();
}

function cancelTimer()
{
  if (closeMenuTimer) {
    window.clearTimeout(closeMenuTimer);
    closeMenuTimer= null;
  }
}

$(document).ready(function(){
  $('#programs').hover(
    function() {
      cancelTimer();
      $('.menudrop').hide();
      closeSubMenu();
      openMenuItem= $(this).children('.topsubmenu').slideDown(slideTime);
    },
    function() {
      closeMenuTimer= window.setTimeout(closeMenus, menuTimeout);
    }
  );
  $('.mainmenuitem').hover(
    function() {
      cancelTimer();
      closeMenus();
      openMenuItem= $(this).children('.menudrop').slideDown(slideTime);
    },
    function() {
      closeMenuTimer= window.setTimeout(closeMenus, menuTimeout);
    }
  );
  $('.mainmenudrop').children('li').hover(
    function() {
      cancelTimer();
      closeSubMenu();
      var subMenu= $(this).children('.submenudrop');
      subMenu.css('margin-left', $(this).width()+12);
      openSubmenuItem= subMenu.slideDown(slideTime);
      return false;
    },
    function() {
      return true;
    }
  );
  $('.submenudrop').children('li').hover(
    function() {
      cancelTimer();
      if ($(this).parent().parent().parent().hasClass('mainmenudrop')) {
        var subMenu= $(this).children('.submenudrop');
        closeSubsubMenu();
        subMenu.css('margin-left', $(this).width()+12);
        openSubsubmenuItem= subMenu.slideDown(slideTime);
      }
      return false;
    },
    function() {
      return true;
    }
  );
  adjustTestimonialHeights();

  $('#dialog-share').dialog({
    autoOpen: false,
    modal: true,
    width: 540,
    buttons: {
      "Share": function() {
        var self = this;

        var to = $( "#share_to" ),
            from = $( "#share_from" ),
            note = $( "#share_note" ),
            allFields = $( [] ).add( to ).add( from ).add( note ),
            tips = $( ".validateTips" );

        var updateTips = function ( t ) {
          tips
            .text( t )
            .addClass( "ui-state-highlight" );
          setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
          }, 500 );
        }

        var checkLength = function ( o, n, min, max ) {
          if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
              min + " and " + max + "." );
            return false;
          } else {
            return true;
          }
        }

        var checkRegexp = function ( o, regexp, n ) {
          if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
          } else {
            return true;
          }
        }

        var bValid = true;
        allFields.removeClass( "ui-state-error" );

        // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
        emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
        if (from === '' || from === null) {
          bValid = false;
          to.addClass('ui-state-error');
          updateTips('Your name must not be blank');
        }

        bValid = bValid && checkRegexp( to, emailRegex, "Invalid email supplied" );

        if ( bValid ) {
          var postData = {
            to: to.val(),
            from: from.val(),
            note: note.val(),
            url: window.location.href
          };

          $.ajax({
            url: '/share-product.php',
            type: 'POST',
            data: "data=" + JSON.stringify(postData),
            processData: false,
            success: function(data) {
              var html = $(self).html();

              var successMessage = $('<p class="success">Product successfully shared</p>');
              $(self).html(successMessage);
              $('#dialog-share').next(".ui-dialog-buttonpane").find('button').attr('disabled', true).addClass('ui-state-disabled');
              setTimeout(function() {
                $('#dialog-share')
                  .next(".ui-dialog-buttonpane")
                  .find('button')
                  .removeAttr('disabled')
                  .removeClass('ui-state-disabled');
                $(self).dialog('close');
                $(self).html(html);
              }, 1000);
            },
            error: function(data) {
              var errorMessage = $('<p class="error">There was an error sharing the page</p>');
              $(self).prepend(errorMessage);

              setTimeout(function() {
                errorMessage.fadeOut(function() {
                  $(this).remove();
                });
              }, 1000)
            }
          });
        }
      },
      Cancel: function() {
        $( this ).dialog( "close" );
      }
    },
    close: function() {
      var to = $( "#share_to" ),
          from = $( "#share_from" ),
          note = $( "#share_note" ),
          allFields = $( [] ).add( to ).add( from ).add( note );

      allFields.val( "" ).removeClass( "ui-state-error" );
    }
  });

  $('.emailpage').click(function(e) {
    $('#dialog-share').dialog('open');
  });
});

function followChildLink(el)
{
  window.location = $(el).children('a').attr('href');
  return false;
}

function adjustTestimonialHeights()
{
  adjustHeights('.testimonial');
}

function adjustHeights(sel)
{
  var group= $(sel);
  var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

function sendTestimonial()
{
  var name= $("input[name='Name']").val();
  if (!name) {
    alert("Please enter your name");
    $("input[name='Name']").focus();
    return;
  }
  var email= $("input[name='Email']").val();
  if (!email) {
    alert("Please enter your e-mail address");
    $("input[name='Email']").focus();
    return;
  }
  var phone= $("input[name='Phone']").val();
  
  var testimonial= $("textarea[name='Testimonial']").val();
  if (!testimonial) {
    alert("Please share your testimonial");
    $("input[name='Testimonial']").focus();
    return;
  }
  
  $.post('/js/send_testimonial.php', {
          name: name,
          email: email,
          phone: phone,
          testimonial: testimonial
  });
}

function slideTestimonial()
{
  var width= 209; // width + margin-right of .testimonial-block element
  var isMax= (parseInt($('.testimonial-slider').css('left'))*-1 + width) >= $('.testimonial-slider').width();
  $('.testimonial-slider').animate({
    left: (isMax ? 0 : ('-='+width))
  });
}

