$(document).ready(function(){

    // Obfuscating the phone number string
    var phone='<li id="phone"><a href="tel:+';
    var phone2='" target="_new" title="Call Chris at work">';
    var phone3='</a></li>';
    var pn='15125516298';
    var pn2_1='(512) 55';
    var pn2_2='1-6298';
    fullnumber=phone+pn+phone2+pn2_1+pn2_2+phone3;
        
    // Detect and defeat orientation change and fullscreen mode
    updateOrientation();
    $("body").addClass("portrait");
    if (navigator.standalone) {
        $("body").addClass("fullscreen");
    } else {
        $("body").addClass("normalscreen");
    }
    
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    	 $("body").addClass("iPhone");
    	 $("#phoneNumberObfuscated").replaceWith(fullnumber);
    	 $("#busCardP2").removeClass("hidden");
    	 $(".pTab a").bind("click", function(){
             iPhoneFlip();
             return false;
         });
         $(".p2sided").addClass("posRel");
         $(".p2sided .page").addClass("posAbs");
    } else {
        $(".pTab a").bind("click",function() {
            toggleCardSides();
            return false;
        });
        // card flipping
        // initialization
        $("#busCardP2").hide();
        $("#busCardP2").scaleY('0');
        $("#busCardP1").show();
    }
    
    window.onorientationchange = function() {
        /*window.orientation returns a value that indicates whether iPhone is in portrait mode, landscape mode with the screen turned to the
        left, or landscape mode with the screen turned to the right. */
        updateOrientation();
    }
    
    // Forms
    // Initialization
    $(".collapse").hide();
    $("#sendByEmail").removeAttr('checked');
    $("#sendBySMS").removeAttr('checked');
    $("#submit").attr("disabled","disabled");
    
    $("input[type='text']").each(function() {
      var $this = $(this);
      $this.attr("title",$("label[for='"+$(this).attr("id")+"']").html())
      $("label[for='"+$(this).attr("id")+"']").hide();
      if($this.val() === '' || $this.val() === $this.attr('title')) {
          $this.addClass('defaultInput');
          $this.removeClass("inError");
          $this.val($this.attr('title'));
      }
      
      $this.focus(function() {
          $this.removeClass("inError");
          $this.removeClass('defaultInput');          
          if($this.val() === $this.attr('title')) {
              $this.val('');
          }
      });
      
      $this.blur(function() {
        if($this.val() === '') {
            $this.addClass('defaultInput');
            $this.val($this.attr('title'));
        }
      });
      
    });
    
    $("a.toggleSwitch").bind("click", function() {
        var checkbox = $(this).siblings('input[type="checkbox"]');
        if (checkbox.is(':checked')) {
            checkbox.removeAttr('checked');
        } else {
            checkbox.attr('checked', 'true');
        }
        updateToggleState( $(this).parent( '.field' ) );
    });
    
    $("#sendByEmail").change(function(){
        updateToggleState( '#fieldEmail' );
        return true;
    });
    
    $("#sendBySMS").change(function(){
        updateToggleState( '#fieldSMS' );
        return true;
    });
    
    updateToggleState( $( '.field' ) );
    
    function updateToggleState( fieldToToggle ) {
        if ($( fieldToToggle ).children( 'input[type="checkbox"]' ).is(':checked')) {
            $( fieldToToggle ).next( '.collapse' ).slideDown();
        } else {
            $( fieldToToggle ).next( '.collapse' ).slideUp();
        }
        validateForm();
    }
        
    $("#emailAddress").blur(function() {
        validateForm();
    });

    $("#smsNumber").blur(function() {
        validateForm();
    });
    
    $("input[name='smsCarrier']").change(function() {
        validateForm();
    });				   

	$("#emailSMSForm").submit(function(){					   				   
        return submitForm();
	});

});

// Orientation change functions
function updateOrientation() {
    var orientation = window.orientation;
    switch(orientation) {
        case 0:
            /* If in portrait mode, sets the body's class attribute to portrait. Consequently, all style definitions matching the body[class="portrait"] declaration
               in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
            $("body").addClass("portrait");
            $("body").removeClass("landscape");
            $("meta[name=viewport]").attr("content","width=device-width");
            /* <meta name="viewport" content="width=320" /> */
        break;  
        case 90:
            /* If in landscape mode with the screen turned to the left, sets the body's class attribute to landscapeLeft. In this case, all style definitions matching the
               body[class="landscapeLeft"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
               $("body").addClass("landscape");
               $("body").removeClass("portrait");
               $("meta[name=viewport]").attr("content","width=device-width");
               
        break;
        case -90:  
            /* If in landscape mode with the screen turned to the right, sets the body's class attribute to landscapeRight. Here, all style definitions matching the 
               body[class="landscapeRight"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
               $("body").addClass("landscape");
               $("body").removeClass("portrait");
               $("meta[name=viewport]").attr("content","width=device-width");
        break;
    }
}

// flip card functions
function iPhoneFlip() {
    if ($("#busCardPIndex").hasClass("flip")) {
        $("#busCardPIndex").removeClass("flip");
    } else {
        $("#busCardPIndex").addClass("flip");
    }
}

function toggleCardSides() {
    if ( !($("#busCardP2 #busCardP1").queue()) ) {
        if (!$("#busCardP2").is(":visible")) {
            $("#busCardP1").animate({scaleY: '0'},function(){
                $("#busCardP1").hide(function() {
                    $("#busCardP2").show(function() {
                        $("#busCardP2").animate({scaleY: '1'});
                    
                    });                    
                });                
            });
        } else if (!$("#busCardP1").is(":visible")) {
            $("#busCardP2").animate({scaleY: '0'},function(){
                $("#busCardP2").hide(function() {
                    $("#busCardP1").show(function() {
                        $("#busCardP1").animate({scaleY: '1'});
                    
                    });                    
                });                
            });
        }
    }
}

// form functions
function submitForm() {
    validateForm();
    $("#submit").fadeTo(600,.5);
    $("#submit").attr("disabled","disabled");
    $("#submit").html("Sending");   
	$.post("sendemail.php",
			{ sendByEmail: $("#sendByEmail").is(':checked'), sendBySMS: $("#sendBySMS").is(':checked'), emailAddress: emailAddressVal, smsNumber: smsNumberVal, smsCarrier: smsCarrierChecked },
				function(data){
				$("#emailSMSForm").slideUp("normal", function() {
				    $("#submit").fadeTo(600,1);
                    $("#submit").removeAttr("disabled");
				    $("#submit").html("Send");
					$("#emailSMSForm").before('<div id="successMessage" style="display:none;"><h1>Success</h1><p>You\'ll be getting a card shortly.</p><button id="sendMore">Send more cards</button></div>');
					$("#successMessage").slideDown();
					$("#sendMore").click(function(){
					    $("#successMessage").slideUp("normal", function() {
					        $("#successMessage").remove();
    					    $("#emailSMSForm").slideDown("normal");
					    });
					});
				});
				}
		 );
	return false;
}

function validateForm() {
    $(".error").remove();
    var hasError = false;
	emailAddressVal = emailAddressValidation();
	smsNumberVal = smsNumberValidation();
    smsCarrierChecked = $("input[name='smsCarrier']:checked").val();
    if (($("#sendByEmail").is(':checked') && !emailAddressVal) || ($("#sendBySMS").is(':checked') && (!smsNumberVal || !smsCarrierChecked)) || (!$("#sendBySMS").is(':checked') && !$("#sendByEmail").is(':checked'))) { //TODO: Add radio button validation
        hasError = true;
    }
    if (!hasError) {
        $("#submit").removeAttr("disabled");
    } else {
        $("#submit").attr("disabled","disabled");
    }
}

// Email validation
function emailAddressValidation() {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var emailAddressVal = $("#emailAddress").val();
    $("#fieldEmailAddress").removeClass("hasError");
    $("#emailAddress").removeClass("inError");
    if(emailAddressVal == '' || emailAddressVal == $("label[for='emailAddress']").html()) {
    	$("#emailAddress").after('<span class="error required">Required</span>');
        $("#fieldEmailAddress").addClass("hasError");
        $("#emailAddress").removeClass("inError");
    	return false;
    } else if(!emailReg.test(emailAddressVal)) {	
    	$("#emailAddress").after('<span class="error">Invalid format</span>');
    	$("#fieldEmailAddress").addClass("hasError");
    	$("#emailAddress").addClass("inError");
    	return false;
    }
	return emailAddressVal;
}

// Email validation
function smsNumberValidation() {
    var smsReg = /^(1{0,1}[0-9]{10})$/;
    var smsNumberVal = $("#smsNumber").val().replace(/[\(\)\s\-\.]/g,"");
    if (smsNumberVal.length == 11) {
        smsNumberVal = smsNumberVal.replace(/1/,"");
    }
    $("#fieldSMSNumber").removeClass("hasError");
    $("#smsNumber").removeClass("inError");    
    if(smsNumberVal == '' || smsNumberVal == $("label[for='smsNumber']").html()) {
    	$("#smsNumber").after('<span class="error required">Required</span>');
    	$("#fieldSMSNumber").addClass("hasError");
        $("#smsNumber").removeClass("inError");    
    	return false;
    } else if(!smsReg.test(smsNumberVal)) {	
        $("#smsNumber").after('<span class="error">Invalid format (U.S. numbers only)</span>');
    	$("#fieldSMSNumber").addClass("hasError");
        $("#smsNumber").addClass("inError");    
    	return false;
    }
	return smsNumberVal;
}
