Event.observe(window, 'load', doFirst);
state = '';

function catchEnterkey(evt) { 
  var evt = (evt) ? evt : ((event) ? event : null); 
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  if ((evt.keyCode == 13) && (node.type == "text")) {
    return false;
  } 
}
document.onkeypress = catchEnterkey;

function doFirst() {
  if($('step2') && $('step3')) { 
    $('step2').hide();
    $('step3').hide();
  }
}
function doSecond() {
  if (checkSteps(1)) {
    new Effect.Fade('step1', { duration:0.2 } );
    var t = setTimeout("$('step2').show();", 300);
	  prepopulation_by_zip($('submission[zip]').value)
	
		//Google Analytics tracking when a user reaches step 2
		pageTracker._trackPageview('/G1_funnel/step-2');
  }
}
function doThird() {
  if (checkSteps(2)){
    new Effect.Fade('step2', { duration:0.2 });
    var t = setTimeout("$('step3').show();", 300);

		//Google Analytics tracking when a user reaches step 3
		pageTracker._trackPageview('/G1_funnel/step-3');
  }
}

function prepopulation_by_zip(zip){
	new Ajax.Request('/landing_page/fetch_zip_data/?zip=' + zip , {asynchronous:false, evalScripts:false});  
}

function populate_state_country(state){
	var objState = document.getElementById("submission[state]");
	var length_state = objState.options.length;	
	
	for (i=0; i<length_state; i++){
		if (objState.options[i].value == state){
			objState.options[i].selected = true;
			break;
		}
	}
	
	var objCountry = document.getElementById("submission[country]");
	objCountry.options[1].selected = true; //Select US
	//Country select. Don't work for now...
	// var length_country = objCountry.options.length;				
	// for (j=0; j<length_county; j++){
	// 	if (objCountry.options[j].value == "US"){ //Hardcoded to US, as we have zips only for US
	// 			objCountry.options[j].selected = true;
	// 			break;
	// 	}				
	// }
}

function checkSteps(n) {
  var unverified_count = 0;

  switch(n) {
    case 1:
      for (i = 0; i < 5; i++) {
        var label_id = 'label_'+i;    
        var label_value = $(label_id).innerHTML;
        var isVerified = verifyOne(label_id, label_value, i);
        if (!isVerified)
          unverified_count++;
      }
      if (unverified_count > 0)  
        return false;
      else
        return true;
      break;
    
    case 2:
      list = document.forms[0].vacation_weeks;
      list_checked = false;
      for (i = 0; i < list.length; i++) {
        list_checked = (list_checked || list[i].checked);
      }
      if (!list_checked) {
        unverified_count++;
        highlightLabel('label_6');
      }
      else unHighlightLabel('label_6');

      list = document.getElementsByName('submission[answer_symbols][]');
      list_checked = false;
      for (i = 0; i < list.length; i++) {
        list_checked = (list_checked || list[i].checked);
      }
      if (!list_checked) {
        unverified_count++;
        highlightLabel('label_7');
      }
      else unHighlightLabel('label_7');

      list = document.forms[0].vacation_budget;
      list_checked = false;
      for (i = 0; i < list.length; i++) {
        list_checked = (list_checked || list[i].checked);
      }
      if (!list_checked) {
        unverified_count++;
        highlightLabel('label_8');
      }
      else unHighlightLabel('label_8');

      if (unverified_count > 0) {
        $('label_9').style.color = '#FF0000';
        return false;
      }
      else
        return true;
      break;

    case 3:
      var phoneStr = $F('submission[phone]'); //Get textfield value (phone number)
      var phoneStripped = phoneStr.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
      var phoneField = $('submission[phone]');
      phoneField.value = phoneStripped; //Set the textfield to stripped value for submission.

      for (i = 11; i < 18; i++) {
	var label_id = 'label_'+i;
	var label_value = $(label_id).innerHTML;
	var isVerified = verifyThree(label_id);
	if (!isVerified)
	unverified_count++;
      }
      if (unverified_count > 0) { 
        $('label_18').style.color = '#FF0000';
        return false;
      }
      else
        return true;
      break;
  }
  return false;
}

function verifyOne(label_id, label_value, i) {
  
  var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;  //simple email check
  var labelExp = /^\*/im; 
  var unverified_count = 0;
  
    if ( document.forms[0].elements[i].value.length < 1 || document.forms[0].elements[i].value.length > 50 || document.forms[0].elements[i].value == '') {
      unverified_count++;
      if ( label_id != 'label_3' ) {
        if ( !($(label_id).innerHTML.match(labelExp)) ) {
          $(label_id).innerHTML = '*'+label_value;
          $(label_id).style.color = '#FF0000';
          $('label_5').style.color = '#FF0000';
        }
      }
    } else { //is valid
  
      if (  label_id != 'label_3' && ($(label_id).innerHTML.match(labelExp)) ) {
        $(label_id).innerHTML = label_value.substr(1);
        $(label_id).style.color = '#333';        
       }
     }
  
  //checking email field separately
  if ( label_id == 'label_3' && (!($('submission[email]').value.match(emailExp)) || $('submission[email]').value.length > 100 ) )  {
    if ( !($(label_id).innerHTML.match(labelExp)) ) {
      $(label_id).innerHTML = '*'+label_value;
      $(label_id).style.color = '#FF0000';
    }
    unverified_count++;
  } else {
    //valid email
    if ( label_id == 'label_3' && ($('submission[email]').value.match(emailExp)) ) {
      if ( ($(label_id).innerHTML.match(labelExp)) ) {
        $(label_id).innerHTML = label_value.substr(1);
        $(label_id).style.color = '#333';        
      }        
    }
  }
  //checking zip field also
  if ( label_id == 'label_4' && $('submission[zip]').value.length > 10 ) {
    if ( !($(label_id).innerHTML.match(labelExp)) ) {
      $(label_id).innerHTML = '*'+label_value;
      $(label_id).style.color = '#FF0000';
    }
    unverified_count++;
  } else {
    //valid zip
    if ( label_id == 'label_4' && ($('submission[email]').value.length < 11 && $('submission[email]').value.length > 0) ) {
      if ( ($(label_id).innerHTML.match(labelExp)) ) {
        $(label_id).innerHTML = label_value.substr(1);
        $(label_id).style.color = '#333';        
      }        
    }
  }
  if (unverified_count > 0)
    return false;
  else
    return true
}

function verifyThree(label_id) {
    unverified_count = 0;
    var phoneExp = /\A[\d]{10,}\Z/;
  
    
    value = $(label_id).nextSibling.nextSibling.value;
    // if label is State/Province
    if (label_id == "label_13") {
      state = value;
    }

    if ((value.length < 1 || value.length > 50 || value.length == '') && label_id != 'label_13')  {
      unverified_count++;
      highlightLabel(label_id);
    } else {
      unHighlightLabel(label_id);
    }
    switch(label_id) {
     
      case "label_14":
      // country/state validation
      // label is Country
        if (!isValidStateCountry(value, state)) {
          highlightLabel('label_13');
          return false;
        }
        else {
          unHighlightLabel('label_13');
          return true;
        }
        
      case "label_15":
      // label is Phone
        if (!isValidPhone(value)) {
          highlightLabel('label_15');
          return false;
        }
        else {
          unHighlightLabel('label_15');
          return true;
        }
    }
    if (unverified_count > 0) return false;
    else return true;
}

function highlightLabel(label_id) {
  if (!($(label_id).innerHTML[0] == '*')) {
    $(label_id).style.color = '#FF0000';
    $(label_id).innerHTML = '*' + $(label_id).innerHTML;
  }
}

function unHighlightLabel(label_id) {
  $(label_id).style.color = '';
  if ($(label_id).innerHTML[0] == '*')
    $(label_id).innerHTML = $(label_id).innerHTML.substr(1);
}

function isValidPhone(value) {
  var phoneExp = /^((.)?[\d]){10,}$/;
  
  if (!value.match(phoneExp) || value.length > 20) {
/*    if (!$('phone_verification')) {
      $('label_15').insert({before: new Element('label', {id: 'phone_verification'}).update('Phone must be at least 10 digits').setStyle({color: '#FF0000'})})  
      $('label_15').insert({before: new Element('div', {'class': 'spacer10', 'id': 'phone_verification_spacer'})})
    }*/
    return false
  }
  else {
    if ($('phone_verification'))
      $('phone_verification').remove();
    if ($('phone_verification_spacer'))
      $('phone_verification_spacer').remove();
    return true;
  }
}

function isValidEmail(email) {
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if (!email.match(emailExp)) {
		return false;
	}
	return true;
}
// trim input to remove trailing characters
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
};

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
};

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
};

function splitStringOnCommas(string) {
	var stringObj = string.replace(/\s/g,"");
		stringObj = trim(stringObj,"\,");
	var stringArray = new Array();
	
	// if user has entered commas, make array
	if (stringObj.indexOf(',') > -1) {
		var stringArray=stringObj.split(",");
		for (var i=0;i<stringArray.length;i++) {
			stringArray[i] = stringArray[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		}
	 }
	// treat input as one email address
	else { 
		stringArray[0] = stringObj;
	}
	return stringArray;
 }

function isValidZip(zip) {
	var valid = "0123456789-";
	var hyphencount = 0;
	// if there are too many characters, return false
	if (zip.length!=5 && zip.length!=10) {
		return false;
	}
	
	// check for valid characters
	for (var i=0; i < zip.length; i++) {
		temp = "" + zip.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			return false;
		}
		// if there is more than a single hyphen in the zip code, or the ten-digit zip code is not formatted correctly return false
		if ((hyphencount > 1) || ((zip.length==10) && ""+zip.charAt(5)!="-")) {
			return false;
		}
	}
	
	return true;
};

function isValidStateCountry(country, state) {
/*  if (!(country == 'CA' || country == 'US') && !(state == '')) {
    if (!$('state_verification')) {
      $('label_13').insert({before: new Element('label', {id: 'state_verification'}).update('State must be blank').setStyle({color: '#FF0000'})})  
      $('label_13').insert({before: new Element('div', {'class': 'spacer10', 'id': 'state_verification_spacer'})})
    }
    return false
  }*/
  
  if (country == '' && state == '') {
    return false
  }
  
  if (country == 'CA' && !findInList(state, CA_PROVINCES)) {
/*    if (!$('state_verification')) {
      $('label_13').insert({before: new Element('label', {id: 'state_verification'}).update('State must be a Canadian province').setStyle({color: '#FF0000'})})  
      $('label_13').insert({before: new Element('div', {'class': 'spacer10', 'id': 'state_verification_spacer'})})
    }*/
    return false
  }
  if (country == 'US' && !findInList(state, US_STATES)) {
/*    if (!$('state_verification')) {
      $('label_13').insert({before: new Element('label', {id: 'state_verification'}).update('State must be a US state').setStyle({color: '#FF0000'})})  
      $('label_13').insert({before: new Element('div', {'class': 'spacer10', 'id': 'state_verification_spacer'})})
    }*/
    return false
  }
  
  if ($('state_verification'))
    $('state_verification').remove();
  if ($('state_verification_spacer'))
    $('state_verification_spacer').remove();
  
  return true;
}

function findInList(state, list) {
  for (j = 0; j < list.length; j++) {
    if (list[j][1] == state)
      return true;
  }
  return false;
}

String.prototype.toTitleCase = function () {
	var A = this.split(' '), B = [];
	for (var i = 0; A[i] !== undefined; i++) {
		B[B.length] = A[i].substr(0, 1).toUpperCase() + A[i].substr(1);
	}
	return B.join(' ');
}