var $j = jQuery;

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

$j('div.flash-caption:empty').remove();

join_list();

if ( $j('#nav ul').length ) {
	mainNav();
}
if ( $j('#group-signup,#team-signup,#women-signup,#moms-signup').length ) {
	$j('.birthdays').blur(function(){
		var birthID = $j(this).attr('name');
		var birth = $j(this).val();
		var d = parseDate(birth);
		if(d==null)
			alert('Please put the date in a readable format'); 
		else {
			$j(this).val(formatDate(d,'MMM dd, yyyy'));
			$j.post('/assets/snippets/get_age.php', { birthday: formatDate(d,'yyyy-MM-dd') },
	   			function(data){
					$j('#submitbutton').before('<input type="hidden" name="'+birthID+'_age" value="'+data+'" />');
	   		});
		}
	});
	$j('div.hidden:last').addClass('last');
	$j('div.col_2 h3:first').addClass('top_h3');
	$j('a#add-child').click(function(e){
		e.preventDefault();
		if ($j('div.hidden:first').hasClass('last'))
			$j('a#add-child').remove();
		$j('div.hidden:first').removeClass('hidden');
	});
	$j('#group-signup,#team-signup,#women-signup,#moms-signup').resetForm();
	$j('#first_choice,#second_choice,#service_area').change(function(){
		$j(this).updateChoice();
	});
	$j('p.choice a').click(function(e){
		e.preventDefault();
		$j(this).setChoice();
	});
	$j('#group_placement').change(function(){
		if ($j(this).val() == 'I\'d like to be placed with my friend')
			$j('#friend-hide').show();
		else
			$j('#friend-hide').hide();
	});
}
if ( $j('#wow,#moms,#group-signup,#team-signup,#women-signup,#moms-signup').length ) {
	wow_form();
}
if ( $j('#invite').length ) {
	friendRefer();
	antiSpam();
}

embedSize();
checkSlideShow();
buttonRoll();
welcomeRoll();
killIE();

$j('a.modal').click(function (e) {
    e.preventDefault();
    $j(this).parent().find('.simplemodal').modal();
});
            
if ( $j('#contact').length ) {
		contact_form();
		}
		
if ( $j('#request').length ) {
		request_form();
		}

});

function embedSize(){
	$j('.img-right embed').attr({'width':'336', 'height':'257'});
	$j('.img-right embed').css('display','block');
}

jQuery.fn.setChoice = function() {
	var optionsGroup = { 
        close:false,
        opacity:0,
		position: ["20%",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer',
		onOpen: function(dialog) {
			dialog.container.fadeIn('fast', function(){
				dialog.data.show();
			});
		}, 
		onShow: function (dialog) {
			dialog.data.find('.message').append('First and Second choices can not be the same. <br />Please choose another group.');
			dialog.data.find('.yes').click(function () {
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.overlay.fadeOut('fast', function () {
						$j.modal.close();
					});
				});
			});
		}
    };
  	var $element = jQuery(this);
  	var $field = $element.attr('rel');
  	var $choice = $element.attr('href');
  	// check to see if the first and second choices are the same
  	if ($element.siblings().hasClass('.active')){
  		$j('#confirm').modal(optionsGroup);
  	} else {
  		// remove active states from all other similar choices
  		$j('a[rel='+$field+']').removeClass('active');
  		// add active state to current clicked choice
  		$element.addClass('active');
  		// set the drop menu to current choice
  		$j('#'+$field).val($choice);
  	}
}

jQuery.fn.updateChoice = function() {
	var optionsGroup = { 
        close:false,
        opacity:0,
		position: ["20%",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer',
		onOpen: function(dialog) {
			dialog.container.fadeIn('fast', function(){
				dialog.data.show();
			});
			}, 
		onShow: function (dialog) {
			dialog.data.find('.message').append('First and Second choices can not be the same. <br />Please choose another group.');
			dialog.data.find('.yes').click(function () {
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.overlay.fadeOut('fast', function () {
						$j.modal.close();
					});
				});
			});
		}
    };
	var $element = jQuery(this);
	var $field = $element.attr('id');
	var $choice = $element.val();
	// check to see if the first and second choices are the same
	if ($field == 'first_choice')
		var $other = $element.nextAll('.chooser').val();
	else
		var $other = $element.prevAll('.chooser').val();
	if ($element.val() == $other){
		$j('a[rel='+$field+']').removeClass('active');
		$j('#confirm').modal(optionsGroup);
		$element.val('Choose');
	} else {
		$j('a[rel='+$field+']').removeClass('active');
		$j('a[rel='+$field+'][href='+$choice+']').addClass('active');
	}
}

function join_list(){
	$j('#joinname').blur(function(){
		val = $j('#joinname').val();
		newVal = '';
		val = val.split(' ');
		for(var c=0; c < val.length; c++) {
		newVal += val[c].substring(0,1).toUpperCase() +
		val[c].substring(1,val[c].length) + ' ';
		}
		$j('#joinname').val(newVal);
	});

	$j('#joinMailList').submit(function(){
		var fullname = $j('#joinname').val();
			if (fullname.indexOf(' ') < 0) {
				alert('Please Enter Your First and Last Name');
				$j('#joinname').focus();
				return false;
			}
			if (echeck($j('#joinemail').val())==false){
				$j('#joinemail').val('');
				$j('#joinemail').focus();
				return false;
			}
		var fullname = fullname.split(' ');
		var name1 = fullname[0];
		var name2 = fullname[1];
		if (name2 == '') {
				alert('Please Enter Your First and Last Name');
				$j('#joinname').focus();
				return false;
			}
		var addy = $j('#joinemail').val();
		$j('a.jml').html('Sending...');
		$j.post('/mail-join.php', { firstname: name1, lastname: name2, email: addy, op: 'set', option: 'subscribe' },
   			function(data){
   			if (data == 'joined'){
   				$j('a.jml').wait(2).then.html('Thank You '+name1+'!');
   				$j('#top').wait(4).then.animate({'height': '0px'}, 700);
	     		$j('a.jml').removeClass('clicked');
	     		$j('#joinemail,#joinname').wait(4.8).then.val('');
   				$
   			} else {
    		 	alert(data);
    		 }
   		});
   		return false;
	});
	
	$j('a.jml').click(function(){
		if ($j(this).hasClass('clicked')) {
		$j('#top').animate({'height': '0px'}, 700);
		$j(this).removeClass('clicked').wait(.8).then.html('Join Our Mailing List');
		} else {
	      $j('#top').animate({'height': '34px'}, 700);
	      $j(this).addClass('clicked').wait(.8).then.html('Close');
	      }
	      return false;
	    });
}

function mainNav() {
	// take over the css and animate instead
	$j('.main_nav li a').attr('title','');
	$j('#nav li ul').css('opacity','0');
	$j('#nav li.active ul').css('opacity','1');
	
	var config = {    
     over: showMenus, // function = onMouseOver callback  
     timeout: 400, // number = milliseconds delay before onMouseOut    
     out: hideMenus // function = onMouseOut callback 
	};

	$j('li.navrow1').hoverIntent(config);
}

function showMenus(){
	if (!$j(this).hasClass('active')){
	$j('#nav li.active ul').css('display','none').css('opacity','0');
	$j(this).addClass('hov');
	$j(this).children('ul').animate({'opacity': '1'}, 'fast');
	}
}

function hideMenus(){
	if (!$j(this).hasClass('active')){
	$j(this).removeClass('hov');
	$j(this).children('ul').animate({'opacity': '0'}, 'fast');
		setTimeout('resetMenu()',150);
	}
	 }
	 
function resetMenu(){
	var n = $j('li.hov').length;
	if	( $j('li.hov').length < 1 ){
	 	$j('#nav li.active ul').css('display','block').animate({'opacity': '1'}, 'fast');
	 }
}

function killIE(){
  if ($j.cookie('killIE') != 'true'){
	if (jQuery.browser.msie) {
	var ie_version = parseInt(jQuery.browser.version);
		if (ie_version < 7){
		$j.cookie('killIE', 'true', { expires: 0, path: '/' });
		window.location = '/ie6_is_bad';
		}
	}
	}
}
	

function checkSlideShow(){
	$j('.flashbox1').prev('p').remove();
}

function welcomeRoll(){
	$j('.cover').animate({'opacity': '0'}, 2000);
	$j('.home_split').hover( 
      function () {
      	var pane = $j(this).attr('class').split(' ').slice(2);
      	$j(this).children('.btn').css('background-position','left bottom');
        $j('#'+pane).stop().animate({'opacity': '.5'}, 400);        
      }, 
      function () {
      	var pane = $j(this).attr('class').split(' ').slice(2);
      	$j(this).children('.btn').css('background-position','left top');
        $j('#'+pane).stop().animate({'opacity': '0'}, 400); 
      }
    );
}

function buttonRoll(){
 if ($j('.btn') != null){
	$j('.btn').hover(
      function () {
        $j(this).css('background-position','left bottom');
      }, 
      function () {
        $j(this).css('background-position','left top');
      }
    );
   }
}

function contact_form(){
var options = { 
        beforeSubmit:  contactWait,
        success:       contactResponse,
        url:       '/assets/snippets/contact_form.php' 
    }; 

var v = $j('#contact').validate({
			submitHandler: function(form) {
				$j(form).ajaxSubmit(options);
				return false;
			}
		});
}

function contactResponse(responseText){
	if (responseText == 'failed'){
	alert('There was a problem sending your request. Please try again later.');
	} else {
	$j('#contact').fadeOut('fast');
	$j('#form_hold').wait(1).then.html('<h2 style="display:none">'+responseText+'</h2>');
	setTimeout('$j(\'#form_hold h2\').fadeIn()',1100);
	}
}

function contactWait(){
	$j('#submitbutton').before('<img id="loader" src="/assets/templates/_images/ajax-loader.gif">');
}

function request_form(){
var options = { 
        beforeSubmit:  requestWait,
        success:       requestResponse    
        }; 

var v = $j('#request').validate({
			submitHandler: function(form) {
				$j(form).ajaxSubmit(options);
				return false;
			}
		});
}

function requestResponse(responseText){
	if (responseText == 'failed'){
	alert('There was a problem sending your request. Please try again later.');
	} else {
	$j('#request, #form_hold h2').fadeOut('fast');
	$j('#form_hold').wait(1).then.html('<h2 style="display:none">'+responseText+'</h2>');
	setTimeout('$j(\'#form_hold h2\').fadeIn()',1100);
	}
}

function requestWait(){
	$j('#submitbutton').before('<img id="loader" src="/assets/templates/_images/ajax-loader.gif">');
}

function wow_form(){
var options = { 
        beforeSubmit:  wowWait,
        success:       wowResponse    
        }; 

var v = $j('#wow,#moms,#group-signup,#team-signup,#women-signup,#moms-signup').validate({
			submitHandler: function(form) {
				$j(form).ajaxSubmit(options);
				return false;
			}
		});
}

function wowResponse(responseText){
	if (responseText == 'failed'){
	alert('There was a problem sending your request. Please try again later.');
	} else {
	$j('#request, #form_hold h2').fadeOut('fast');
	$j('#form_hold').wait(1).then.html('<h2 style="display:none">'+responseText+'</h2>');
	setTimeout('$j(\'#form_hold h2\').fadeIn()',1100);
	}
}

function wowWait(){
	$j('#submitbutton').before('<img id="loader" src="/assets/templates/_images/ajax-loader.gif">');
}

function friendRefer(){
	$j('input[title!=""]').hint();
	$j('#antiSpam').val('Please do not alter');
	$j('#friend_name').blur(function(){
		val = $j('#friend_name').val();
		newVal = '';
		val = val.split(' ');
		for(var c=0; c < val.length; c++) {
		newVal += val[c].substring(0,1).toUpperCase() +
		val[c].substring(1,val[c].length) + ' ';
		}
		$j('#friend_name').val(newVal);
		});
		
	$j('#btn_invite').click(function(){
		$j('#answer').remove();
		var spamcheck = $j('#antiSpam').val();
		var fullname = $j('#friend_name').val();
		var name1 = fullname[0];
		var name2 = fullname[1];
		var friendmail = $j('#friend_email').val();
		var newseries = $j('#front-left h2 span').html();
		if (fullname.indexOf(' ') < 0) {
				alert('Please Enter Your First and Last Name');
				$j('#name').focus();
				return false;
			}
			if (echeck($j('#friend_email').val())==false){
				$j('#friend_email').val('');
				$j('#friend_email').focus();
				return false;
			}
			if (name2 == '') {
				alert('Please Enter Your First and Last Name');
				$j('#name').focus();
				return false;
			}
		$j('#btn_invite').after('<img id="loader_friend" src="/assets/templates/_images/ajax-loader.gif">');
		$j.post('/our-services/refer', { name: fullname, email: friendmail, series: newseries, antiSpam: spamcheck },
   			function(data){
   				$j('#loader_friend').fadeOut();
   				$j('#btn_invite').after('<div id="answer" style="display:none">'+data+'</div>');
   				$j('#answer').wait(1).then.fadeIn();
   				$j('#loader_friend').wait(2).then.remove();
   		});
	return false;
	});
}


// method for chaining and pausing jquery events
var ChainCollector = function(base) {
var CLASS = arguments.callee;
this.then = this.and = this;
var queue = [], baseObject = base || {};
this.____ = function(method, args) {
queue.push({func: method, args: args});
};
this.fire = function(base) {
var object = base || baseObject, method, property;
for (var i = 0, n = queue.length; i < n; i++) {
method = queue[i];
if (object instanceof CLASS) {
object.____(method.func, method.args);
continue;
}
property = object[method.func];
object = (typeof property == 'function')
? property.apply(object, method.args)
: property;
}
return object;
};
};
ChainCollector.addMethods = function(object) {
var methods = [], property, i, n, name;
var self = this.prototype;
var reservedNames = [], blank = new this();
for (property in blank) reservedNames.push(property);
var re = new RegExp('^(?:' + reservedNames.join('|') + ')$j');
for (property in object) {
if (Number(property) != property)
methods.push(property);
}
if (object instanceof Array) {
for (i = 0, n = object.length; i < n; i++) {
if (typeof object[i] == 'string')
methods.push(object[i]);
}
}
for (i = 0, n = methods.length ; i < n; i++)
(function(name) {
if (re.test(name)) return;
self[name] = function() {
this.____(name, arguments);
return this;
};
})(methods[i]);
if (object.prototype)
this.addMethods(object.prototype);
};
jQuery.fn.wait = function(time) {
var collector = new ChainCollector(), self = this;
// Deal with scoping issues...
var fire = function() { collector.fire(self); };
setTimeout(fire, Number(time) * 1000);
return collector;
};
// Then extend ChainCollector with all jQuery's methods
ChainCollector.addMethods(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// some simple email validation
function echeck(str) {
var message = 'Please Enter a Valid Email Address!';
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert(message)
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert(message)
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert(message)
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert(message)
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert(message)
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert(message)
return false
}
if (str.indexOf(" ")!=-1){
alert(message)
return false
}
return true					
}

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);

// some anti-spam help
var antiSpam = function() {
        if ( $j('#antiSpam').length ) {
                a = $j('#antiSpam');
                if (isNaN(a.val()) == true) {
                        a.val(0);
                } else {
                        a.val(parseInt(a.val()) + 1);
                }
        }
        setTimeout("antiSpam()", 2000);
}

antiSpam();