﻿var emailDialogW = parseInt("574");
var boxHeight = parseInt("215");
var heightToAdd = 0;
var dialogX = 0;
var incPerErrorRow = 15;
var emailErrors = new Array();
var emailValidationTypes = null;
var email_page = "";
var email_pageTitle = "";

/***************************** Utilities Main Window ********************************/

function getSecureRoot(){
	var url = window.location.href.toLowerCase();
	var dir = "sites/mttq";
	var urlSecureRoot = url.substr(0,url.lastIndexOf(dir)+dir.length);
	if(url.indexOf("https://") == -1){
		url = urlSecureRoot.replace("http","https");
	}else{
		url = urlSecureRoot;
	}
	return url;
}

function initEmailDialog(){
  try{
  	  $('#emailDialog').dialog("destroy");
      $('#emailDialog').dialog({
		    autoOpen: false,
		    minHeight:boxHeight+100,
		    minWidth:emailDialogW,
		    width:emailDialogW,				   
		    modal:true,
		    resizable:false,
		    create: function(event, ui) {
		    	$('.ui-widget-header').css('display','none');	   
			    $('.ui-dialog-titlebar').css('display','none');
				$('.ui-dialog').css({'border' : '0px', 'padding' : '0px'});
			    $('.ui-dialog-content').css({'border' : '0px', 'padding' : '0px'});
		    },
		    open:function(event, ui) {
		    	/***************************** Close Window ********************************/
			    $('.overlayCloseBtn').click(function(e){
			         e.preventDefault();
					 try{
			            $("#emailDialog").dialog('close');
			         }catch(ee){}
			    });
			    /***************************** PlaceHolders ********************************/
				$("#refPageTitleInEmail1,#refPageTitleInEmail2").html(email_pageTitle);
				$("#refPageLinkInEmail").attr('href',email_page);
				$("#refPageLinkInEmail").html(email_page.replace("/mttq/pages/","/mttq/pages/<br/>"));
				/***************************** Frame ***************************************/
				var httpsRoot = getSecureRoot(); // https://marketingweb.pfizer.com/sites/MTTQ
				$("#emailFrame").attr("height", boxHeight);
				$("#emailFrame").attr("src", httpsRoot + "/Html Library/email_to_a_friend_frame.html?email=" + encodeURIComponent(email_page) + "&title=" + encodeURIComponent(email_pageTitle) + "&c="  + Math.random());
				/***************************** View ****************************************/
				$("#emailFormWrapper .topFormText").css('display','block'); 
				$('#emailConfirmWrapper').hide();
	        	moveActiveDialog();         	
	        }
      });
      $('#emailDialog').dialog('open');
  }catch(ee){alert(ee.message);}
}

function findWindowPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft+=obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.x) {
        curleft+=obj.x;
    }
    return curleft;
}

function findXPositionOfEmailDialog(){
    var contentX = findWindowPosX(document.getElementById("content"));
    if(contentX <= 235){ contentX = 235; }
    var contentW = $("#content").outerWidth(true);
    return parseInt("" + (contentX + ((contentW - emailDialogW)/2)) + "");
}

function moveActiveDialog(dx,dy){
	if(!dx)	dx = findXPositionOfEmailDialog();
	if(!dy) dy = 100;
	if(dx != dialogX){
		dialogX = dx;
		$('#emailDialog').dialog('option','position',[dx,dy]);
	}
}

function getQuerystring(key){
    var url=location.href.toLowerCase();
    url=url.substr(0,url.lastIndexOf(".aspx")+5);   
    if (url==null) url=""; 
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if(qs == null)
    return url;
    else
    return qs[1];
}

/***************************** Utilities Dialog Window ********************************/

function passMessage(msg) {
    window.parent.location.href = email_page + "#" + msg;
}

/***************************** Initialize box ****************************/

// Parent and dialog document ready
$(document).ready(function() {
	
	// Main window
	if(!$("body").hasClass("emailAFriendFrame")){
	
		email_pageTitle = document.title;
		email_page = window.location.href.toLowerCase();
	
		/********************* Window Pass Message Reader *************************/
		window.setInterval(function() {
            var loc = window.location.href;
            if (loc.indexOf("#") >= 0) {
                var msg = loc.substr(loc.lastIndexOf("#") + 1);
                if (msg.indexOf("height") >= 0) {
                    var height = msg.replace("height=", "");
                    $("#emailFrame").attr("height", height);
                } else if (msg.indexOf("setRN") >= 0) {
                	var rn = decodeURI(msg.replace("setRN=", ""));
                	$("#recipientNameInEmail").html(rn);
                } else if (msg.indexOf("success") >= 0) {
					$("#emailConfirmWrapper").fadeIn('slow');
					$(".topFormText").fadeOut('fast'); // ?
					$("#emailConfirmTopFormText").fadeIn('slow'); // ?
					$("#recipientNameInEmail").html("");
					$("#emailFrame").attr("height", boxHeight);
                } else if (msg.indexOf("close") >= 0) {
                    $("#emailDialog").dialog('close');
                }
                window.location.href = "#";
        	}
        }, 500);
	
		/***************************** Open Window ********************************/
		$('a.emailPopupLink').click(function(e) {
	 		e.preventDefault();
	 	 	try{
		      initEmailDialog();
		   	  return false;
	       }catch(ee){alert(ee.message);}
 		});
 		
 		/************************* Window Resize Event ****************************/
 		$(window).resize(function(){
			try{
				if ($('#emailDialog').dialog('isOpen') == true){
			      	moveActiveDialog();
			    }
			}catch(i){alert(i.message)}
		});
	    
	}else{
	// Frame Window
	
		email_pageTitle = decodeURIComponent(getQuerystring('title'));
		email_page = decodeURIComponent(getQuerystring('email'));

		/***************************** Validation ********************************/
		emailValidationTypes = new Array("requiredField","email");
	    emailErrors["txtSenderName.requiredField"] = "Please include your name";
	    emailErrors["txtSenderEmail.requiredField"] = "Please include your e-mail";
	    emailErrors["txtRecipientName.requiredField"] = "Please include your friend\'s name";    
	    emailErrors["txtRecipientEmail.requiredField"] = "Please include your friend\'s e-mail";
	    emailErrors["txtSenderEmail.email"] = "Please enter your e-mail address in the form of name@domain.com.";
	    emailErrors["txtRecipientEmail.email"] = "Please enter your friend\'s e-mail address in the form of name@domain.com.";  
	    clearErrors($("#EmailAFriendForm"),emailValidationTypes);
	    	
		/***************************** Submit form ********************************/
	    $('#emailSubmit').click(function() {
	     	// Fill hidden variables
			$("input#hdnPreviousURL").val(email_page);
	     	$("input#txtMessage").val(email_pageTitle);	
	     	$("input#txtSubject").val(email_pageTitle + " - www.MyTimeToQuit.com");	     	 
	    });
	    $("#EmailAFriendForm").submit(function(){ 
	      try{
	        clearErrors($("#EmailAFriendForm"),emailValidationTypes);
			if(isValid($("#EmailAFriendForm"),emailValidationTypes)){				
			    $.post(  
		            "/sites/mttq/pages/controller.aspx",  
		            $("#EmailAFriendForm").serialize(),  
		            function(data){ 
		            	// On Sent Email Success
		                if(data.indexOf("invalid.html") == -1){
		                	passMessage("success");
							$("#txtRecipientName, #txtRecipientEmail").val('');
						}else{
						// On Sent Email Fail
							// alert('data not success' + data);
						}
		            } //func
		        );  //post
			    return false;
			}else{
			    for( var i= 0;i<errorList.length;i++){
			    	showErrorFor(errorList[i].element, errorList[i].validationType, emailErrors);
			    }
			    // Increase box height
			    heightToAdd += errorList.length*incPerErrorRow;
			    if($("#errortxtSenderEmail").html() == emailErrors["txtSenderEmail.email"]){ heightToAdd += incPerErrorRow; }
			    if($("#errortxtRecipientEmail").html() == emailErrors["txtRecipientEmail.email"]){ heightToAdd += incPerErrorRow; }
				if(heightToAdd!=0){
					passMessage('height='+(heightToAdd+boxHeight));
					heightToAdd = 0;	
				}
			    return false;
			}
		  }catch(ee){alert(ee.message);}
		});
	    	    
	    /***************************** Presentation ******************************/
	    $('#emailFormWrapper').fadeIn('slow');
	    // Fill Sample Recipient name
	    $("input#txtRecipientName").blur(function(e){
			passMessage("setRN=" + encodeURI($(this).val()))
	    });
	    
	}
     
})
