$(document).ready(function() {
  var today = new Date(); 
  var todayPlus3 = new Date();todayPlus3.setDate(todayPlus3.getDate()+3);
  var dateCheck = 1;
  
  //Dialog windows from JQuery UI
  $('#dialog').dialog({autoOpen: false,modal: true,width:500,height:380,resizable: false,bgiframe: true});
  $('#dialogPurpose').dialog({autoOpen: false,modal: true,width:500,height:380,resizable: false,bgiframe: true});
  $('#dialogRecognition').dialog({autoOpen: false,modal: true,width:500,height:380,resizable: false,bgiframe: true});
  $('#calendarWarningPrev').dialog({autoOpen: false,modal: true,width:500,height:280,resizable: false,bgiframe: true});
  $('#calendarWarningThreeDays').dialog({autoOpen: false,modal: true,width:500,height:280,resizable: false,bgiframe: true});
  $('.opener').click(function() {$('#dialog').dialog('open');return false;});
  $('.openerPurpose').click(function() {$('#dialogPurpose').dialog('open');return false;});
  $('.openerRecognition').click(function() {$('#dialogRecognition').dialog('open');return false;});
  $('#reloadCaptcha').click(function(){reloadCaptchaImage();return false;});
  
  
  //determine which step to show onload
  showStep();
    
  //step button actions
  $('#continuebutton').click(function(){
    if (validator('firstStep')) {
      showStep(2);
      $.scrollTo($('#lastStep'), 800, {axis: 'y'});
    }
  });
  $('#backbutton').click(function(){
    showStep(1);
    $.scrollTo($('#firstStep'), 800, {axis:'y'});
  });
  
  $('#submitbutton').click(function(){
    if (validator('lastStep')) {
      $('#DonationRequestForm').submit();
    }
  });
  
  $("#DonationRequestForm").validate();

  


  
  //resets background color for required fields
  $('.requiredField').focus(function(){
    $(this).attr('style', '');
    $('.requiredErrorMsg').hide();
  });
  
  //Datepicker function from JQuery UI
  $('#date-input-1').datepicker({onSelect: function(value, date) {	
	  var thisDate = makeDate($(this).val());
      $('#DonationExpedite').val(0);
	  dateCheck=0;
		
		if (thisDate < today) {
  			$('#calendarWarningPrev').dialog('open');
  			return false;
  		}
  		else if ((thisDate >= today) && (thisDate<= todayPlus3)) {
  			$('#calendarWarningThreeDays').dialog('open');
			$('#DonationExpedite').val(1);
        
  			return false;
  		}  
	}, 
  	showOn: 'button', minDate: 1, buttonImageOnly: true, buttonImage: '/images/calendar_icon.gif', dateFormat: 'mm-dd-yy'
  });
  
  //Mask Input
  $("input.phone").mask("(999) 999-9999");
  $("input.zipcode").mask("99999");
  
  $("input#date-input-1").blur(function(){
	if($(this).val().length >> 0  && $(this).val().length <=  9 && dateCheck==1 ){
		alert("Please check your date format. Must be MM-DD-YYYY");
	}	
  });
  
  $("input#date-input-1").click(function(){
	dateCheck=1;
	
  });
  
  $(".ui-datepicker-trigger").click(function(){
	dateCheck=0;	
  });
  
  
  
  //dynamic dropdown menus for the sponsorship document
  $("#DonationSpecificRequestContainer div").hide();
  $('#DonationSpecificRequest').change(function() {
  	$.each($.viewMap, function() { this.hide();this.find('input').attr('class','');});
  	
    $.viewMap[$(this).val()].show();
    $.viewMap[$(this).val()].find('input').attr('class','requiredField');
    
  });
  $.viewMap = {
  	'' : $([]),
    'Sponsorship' : $('#view1'),
  	'Gift Card' : $('#view2'),
  	'Gift Basket' : $('#view3'),
  	'Food' : $('#view4'),
  	'Fundraiser' : $([]),
  	'Other' : $('#view6')
  	
  };



});

function makeDate(date){
	var thisDate = new Date(date.replace(/-/g, "/"));
	return thisDate;
}

//formatting the date for the "Event Date" input field 
function formatDate(date){
  var d = date;
  var curr_date = d.getDate();
  if(curr_date <= 9){
    curr_date = "0"+curr_date.toString();
  }
  var curr_month = d.getMonth();
  curr_month++;
  if(curr_month <= 9){
    curr_month = "0"+curr_month.toString();
  }
  var curr_year = d.getFullYear();
  thisDate = curr_month + "-" + curr_date + "-" + curr_year;  
  return thisDate;
  
  
} 	

function loadAjaxAfterNext(){
      reloadCaptchaImage();
      if($('#DonationStoreState').val() == "" || $('#DonationStoreState').val() == null){
        var storeUrlStr = '/donations/storeDropdown/'; 
        if (storeStateValue) {
          storeUrlStr = storeUrlStr+storeStateValue;
          if(storeCityValue){
            storeUrlStr = storeUrlStr+'/'+storeCityValue;
            if(storeAddressValue){
              storeUrlStr = storeUrlStr+'/'+storeAddressValue;
            }
          }
        }
        loadAjax(storeUrlStr, 'storeAjax');       
      }
  }

function reloadCaptchaImage(){
  $('#captcha').attr('src','/captchas/image/' + Math.random());
  $('.donationCaptcha input').val('');
  return false;
}




function showStep(step){
  if (!step) {
    step = $.getUrlVar('step');
  }
  if(!step || step == null || step == '1'){
    $('#firstStep').fadeIn(1200);
    $('#lastStep').hide();
  }
  else{
    $('#firstStep').hide();
    $('#lastStep').fadeIn(1200);
  }
  
}


function validator(stepID){
  var valid = true;
  
  $('#'+stepID+' .requiredField').each(function(index) {
    if($(this).val() == null || $(this).val() == ""){
      valid = false;
      $(this).attr('style', 'background-color:#FFDE00;');
      $('#'+stepID+' .requiredErrorMsg').show();      
    }
    else{
      $(this).attr('style', '');
    }
  });
  return valid;
}

function isValidEmailAddress(emailAddress) {
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

//adds getUrlVar as a jQuery extension
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

