jQuery(function(){

  var cfg = {
              speed:slideDuration,
              slideDirection:slideDirection,
              slideTransitionSpeed:800,
              transitionEasing:'easeOutExpo',
              regEasing:'easeOutBounce',
              useAnimations:true
            },
	timeTaken,
	startTime = +new Date();
	
	//check execution speed
	for (i = 0; i < 999999; i++){
		// ...
	}

  timeTaken = (+new Date()) - startTime; // calculate the time taken

  if (timeTaken > 500){
    //set the slidshow config obj to not use animations
    cfg.useAnimations = false;
  }
  //end check execution


  //init the slideshow
  $('#slideShow')
    .addClass('withJS')
    .mtSlideShow(cfg);

	if (hasError){
		$('#openRegButton').trigger('click');
        $('#submitRegButton').trigger('click');
        hasError = false;
    }
});




(function( $ ){
  $.fn.mtSlideShow= function(cfg) {

    var defaults = {
        speed : 5000,                 //time between slides
        slideDirection : 1,           //direction (X axis) that slide is animated
        willStartTime : speed/2,      //time to wait after manually advancing to start the slideshow again
        dName : 'mtSlideShow',        //name to store pugin data under using jQuery data()
        slideTransitionSpeed : 800,   //slide transition speed
        transitionEasing:'swing',     //easing function to use for the slide animation
        regEasing:'swing',            //easing function to use for the registration form animation
        captionShowSpeed : 400,       //how fast to fade in the caption
        captionHideSpeed : 200,       //how fast to fade out the caption
        useAnimations : true          //set to false to disable all animations (for slow computers)
    },
    o = $.extend(defaults,cfg);

    var speed = o.speed,
        willStartTime = o.willStartTime,
        ss = this,
        ssWrapper = $(),
        slides = this.children('.slide'),
        regForm = $('#landingRegForm').css('opacity','.5'),
        regFormWrap = $('#landingFormWrap'),
        regFormError = $('#landingFormError'),
        dName = o.dName,
        ccopy = '',
        slideTransitionSpeed = o.slideTransitionSpeed,
        captionShowSpeed = o.captionShowSpeed,
        captionHideSpeed = o.captionHideSpeed;

    //set up the initial slideshow data
    ss.data(dName,{speed:speed,interval:-1,slides:slides,activeSlide:-1});

    //set up the show registration and submit form links/buttons
    $('#topRegLink,#openRegButton,#submitRegButton').live('click',function(e){
      e.stopPropagation();
      e.preventDefault();

      var thisId = $(this).attr('id');

      if (thisId == 'submitRegButton'){
        //submit the form
        regForm.submit();
      }else{
        //show the reg form/submit button and stop the slideshow
        if (o.useAnimations){
          regForm.animate({left:0,opacity:1},800,o.regEasing,function(){ regForm.find('input[type="text"]:first').focus(); });
        }else{
          regForm.css({left:0,opacity:1});
          regForm.find('input[type="text"]:first').focus();
        }

        $('#openRegButton').fadeOut(200);
        $('#submitRegButton').fadeIn(300);
        toggleSlideShow('stop');
      }
    });

    //clicking the slide will either close the error and reg form or go to the next slide
    $('#slideShow').live('click',function(e){
        if (regFormError.css('right')!='-340px'){
            if (o.useAnimations){
                regFormError.animate({right:'-340px',opacity:0},800,o.regEasing,
                    function(){
                        regFormError.parent().css('zIndex',1);
                    });
            }else{
                regForm.css({right:'-340px',opacity:0});
                regFormError.parent().css('zIndex',1);
            }
        }
        if (regForm.css('left')=='0px'){
            if (o.useAnimations){
                regForm.animate({left:"-"+regFormWrap.width(),opacity:.5},800,o.regEasing);
                $('#submitRegButton').fadeOut(200);
                $('#openRegButton').fadeIn(300);
            }else{
                regForm.css({left:regFormWrap.width()*-1,opacity:.5});
                //console.log(regFormWrap.width(), regForm, regForm.css('left'));
                $('#submitRegButton').css('display','none');
                $('#openRegButton').css('display','block');
            }

            toggleSlideShow();
        }else{
          toggleSlideShow('stop');
          ss.data(dName).willStop = setTimeout(function(){toggleSlideShow('start');},willStartTime);
          
          if (e.target.parentNode.getAttribute('id') == 'prev'){
            nextSlide('reverse'); // pass in a value (any value but null) to reverse the direction
          }else{
            nextSlide();
          }
        }
    });
    
    //prevent default action on the next and prev anchors
    $('#slideShow #next a, #slideShow #prev a').live('click',function(e){ e.preventDefault(); });
    
    //stop the event bubbling for the form/error to prevent it from hiding
    regForm.live('click',function(e){ e.stopPropagation(); });
    regFormError.live('click',function(e){ e.stopPropagation(); });

    //set up enter to submit the form just in case
    regForm.live('keypress',function(e){
      if (e.keyCode == 13){
        e.preventDefault();
        $(this).submit();
        //return false;
      }
    });

    //registration form onSubmit validation
    regForm.submit(function(){
      //regform js validation
      var valid = true,
          invEmpty = [],
          nameMapping = { //matches up with the input ids/names to give validation error description to the user
            ApplicantName : 'User Name',
            ApplicantPassword : 'Password',
            ApplicantPasswordConfirm : 'Confirm Password'
          },
          msg = '';

      regForm.find('input[type="text"], input[type="password"]').each(function(){
        var $this = $(this);

        //empty value check
        if ($.trim($this.val()) == ''){
          valid = false;
          invEmpty.push(nameMapping[$this.attr('id')])
        }
      });

      if (invEmpty.length>0){
        msg += invEmpty.join(', ') + ' cannot be empty. \n\n';
      }

      //passwords have to match but only if it is still valid so far
      if ($('#ApplicantPassword').val() != $('#ApplicantPasswordConfirm').val() && valid === true) {
        valid = false;
        msg += 'Passwords do not match. \n\n';
      }
      
      if (hasError){
		valid = false;
        msg = $("#innerError").text();
      }

      if (valid === false){
		if (!cssErrors)
			alert(msg);
		else
		{
			//show the error
			regFormError.parent().css('zIndex',1000);

			if (o.useAnimations){
				if (parseInt(regFormError.css("right"),10) == 0){
					$("#innerError").stop().fadeOut(300,function(){ $("#innerError").text(msg).fadeIn(500,function(){ $("#innerError").css('opacity',1); }); });
				}else {
					$("#innerError").text(msg);
				}
				regFormError.animate({right:0,opacity:1},800,o.regEasing);
			}else{
				regFormError.css({right:0,opacity:1});
				$("#innerError").text(msg);
			}
		}        

      }else {
        //hide the error?
      }

      return valid;
    });

    //set up the slides
    slides.each(function(i){
        var thisSlide = $(this),
            caption = thisSlide.find('.caption').hide();
        thisSlide.data(dName,{index:i,active:false,caption:caption,willStart:false});

        //hide all but the first slide
        if (i == 0){
          thisSlide.data(dName).active = true;
          ss.data(dName).activeSlide = thisSlide;

          var captionBG = thisSlide.find('div.captionBG');
          cbgcopy = captionBG.clone().appendTo(ss);
          ccopy = caption.clone().appendTo(ss).css('display','block');

        }else{
          thisSlide.css({'left':ss.width()*o.slideDirection*-1,opacity:0});
        }
    });

    //starts and stops the slideshow
    //if no action is given it just toggles
    function toggleSlideShow(action){
        switch (action){
          case 'start':
            if (ss.data(dName).interval == -1){
                ss.data(dName).interval = setInterval(function(){
                nextSlide();
              },speed);
            }
            break;
          case 'stop':
            if (ss.data(dName).interval > -1){
                clearInterval(ss.data(dName).interval);
                ss.data(dName).interval = -1;
            }
            break
          default:
            if (ss.data(dName).interval == -1){
                ss.data(dName).interval = setInterval(function(){
                nextSlide();
              },speed);
            }else{
                clearInterval(ss.data(dName).interval);
                ss.data(dName).interval = -1;
            }
        }
    }

    //goes to the next or previous slide
    function nextSlide(reverse){
      var thisSlide = ss.data(dName).activeSlide,
          slideDirection = (typeof reverse != 'undefined') ? o.slideDirection*-1 : o.slideDirection,
          //direction = (slideDirection < 0) ? "left" : "right",
          nextIndex = (typeof reverse != 'undefined') ? thisSlide.data(dName).index-1 : thisSlide.data(dName).index+1,
          nextSlide = (nextIndex > slides.length-1 ) ? $(slides[0]) : (nextIndex < 0) ? $(slides[slides.length-1]) : $(slides[nextIndex]);

        thisSlide.css({zIndex:2});

        //slide transition effect
        nextSlide
          .css({zIndex:3,left:ss.width()*slideDirection*-1});

        if (o.useAnimations){
           thisSlide.stop(true,true);
           nextSlide
              .animate({left:0,opacity:1},slideTransitionSpeed,o.transitionEasing,function(){
                        thisSlide.css({opacity:0,zIndex:1});
                  });

            //show the caption text
            ccopy.stop(true,true).fadeOut(captionHideSpeed,function(){
              ccopy.html(nextSlide.data(dName).caption.html()).fadeIn(captionShowSpeed);
            });
        }else{
            nextSlide.css({'left':0,opacity:1});
            thisSlide.css({'opacity':0});

            //show the caption text
            ccopy.html(nextSlide.data(dName).caption.html())
        }
        ss.data(dName).activeSlide = nextSlide;
    }

    //start the slide show
    toggleSlideShow();
  };
})( jQuery );


