//
//  Globals
//
var gPopupForm; // Will be set to the jQuery pop up object
var popUrl = "";  // The string url of the pop up defined in displayVideoRequest()
var popupVisible = false;  // Will not be needed in one minute
var in7dayhold = false;  // If true, wait 7 days after the form submission before displaying the pop-up for the idea kit.

if (typeof(DontShowClickPopup) == 'undefined') {DontShowClickPopup = false;}  // May be defined in the main html file
if (typeof(timeBasedPopup) =='undefined') {timeBasedPopup="";}  // May be defined in the main html file
if (typeof(timeBasedTimer1)=='undefined') {timeBasedTimer1= 5000;}
if (typeof(timeBasedTimer2)=='undefined') {timeBasedTimer2= 5000;}

//
//  Load in the cookie values
//
var clickedCount = parseInt(getCookieValue('clickedLinkCount',0));  // load the current click count from the cookie
var popupPresentedCount = parseInt(getCookieValue('popupPresentedCount',0));
var LandingPageURL = getCookieValue('LandingPageURL','');

var videoRequested = getCookieValue('VideoRequested','N');
var ideaKitRequested = getCookieValue('IdeaKitRequested','N');

var lastPopupDate = new Date();
lastPopupDate = getCookieValue('lastPopupDate',0);

var formSubmissionDate = new Date();
formSubmissionDate = getCookieValue('formSubmissionDate',0);

//
//  Attach an event listener to each link on the page to count clicks
//
function setupLinksForCounting() {
	jQuery('a').click(function(){
		var cookieName = "clickedLinkCount";
		var cookieValue = getCookieValue(cookieName);
		if (cookieValue && cookieValue != "NaN") {
			cookieValue = cookieValue * 1;
			cookieValue += 1;
		}
		else {
			cookieValue = 1;
		}
		createCookie(cookieName, cookieValue, 365);
	});
}

//
//  Define logic for clearing click counts and dismissal counts after a number of days
//
function checkPopUpCycle() {
  if (ideaKitRequested=="N") {
    if ((videoRequested=="N") && (lastPopupDate!=0)) {
      var dt = new Date(lastPopupDate);
      dt.setDate(dt.getDate() + 7);
      if (dt<Date()) {
        clickedCount = 0;
        popupPresentedCount = 0;
        lastPopupDate = 0;
        createCookie('clickedCount', 0, 365);
        createCookie('popupPresentedCount', 0, 365);
        createCookie('lastPopupDate', 0, 365);
        } 
    }
    if ((videoRequested=="Y") && (formSubmissionDate!=0)){
      var dt = new Date(formSubmissionDate);
      dt.setDate(dt.getDate() + 7);
      if (dt<Date()) {
        clickedCount = 0;
        popupPresentedCount = 0;
        formSubmissionDate = 0;
        createCookie('clickedCount', 0, 365);
        createCookie('popupPresentedCount', 0, 365);
        createCookie('formSubmissionDate', 0, 365);
        } else {
        in7dayhold=true;
        }
    }
  }
}

//
//  Determine which pop up to pop up -- called once by displayVideoRequest()
//
function getPopURL(resetCurrentPopup) {
    if (typeof resetCurrentPopup == 'undefined') {
	resetCurrentPopup = false;
    }
    
    var popUrl = '/all/popup/generalDivPopup2.html?Clicked=' + clickedCount + '&Presented=' + popupPresentedCount + '&LandingPageURL=' + LandingPageURL;
    epOriginalLabelColor = 'black';
    
    if (timeBasedPopup == "SwimSpa") {
    // On whatis/jetted_swim_spas.html
	var popUrl = '/all/popup/swimSpaDivPopup1.html';
	epOriginalLabelColor = 'black';
    }

    if (timeBasedPopup == "LapPool") {
    // On tour/index.html
	var popUrl = '/all/popup/lapPoolDivPopup1.html';
	epOriginalLabelColor = 'black';
    }

    if (timeBasedPopup=="WaterWell") {
    // On waterwell/index.html
	var popUrl = '/all/popup/waterWellDivPopup1.html';
	epOriginalLabelColor = 'black';
    }

    if (typeof doideaKitPopup != 'undefined' && doideaKitPopup == true) {
	var popUrl = '/all/popup/freeIdeaKitDivPopup1.html';
	epOriginalLabelColor = 'black';
    }

    if (timeBasedPopup=="OpenWater") {
    // On why/swimtraining/openwatertraining.html
	var popUrl = '/all/popup/openWaterDivPopup1.html';
	epOriginalLabelColor = 'black';
    }

    //alert(popUrl);
    return popUrl;
}

//
//  Display the pop up and log an event PopUp Presented
//
function setHiddenLandingScriptVal(L) {
    jQuery("input[name='LandingScript']").val(L);
}

function setRequired(FieldID) {
    jQuery('#' + FieldID).addClass('form_required');
}

function displayVideoRequest() {
	popUrl = getPopURL(false);
	

	jQuery("embed").hide();

	jQuery.ajax({
	    url: popUrl,
	    type:'GET',
	    dataType:'html',
	    async:'false',
	    timeOut:10000,
	    success: function(html) {
		  gPopupForm = Dialog.info(html, { windowParameters: {
		    id:"gPopupForm", 
		    resizable: false, 
		    width: 800, 
		    height:450, 
		    destroyOnClose: true,
				toTop:true,
				onClose: function(){
					jQuery("embed").show();
					
				},
		    onShow: function() {
		      setRequired('FirstConTitle'); 
		      setRequired('ContactFirst'); 
		      setRequired('ContactLast'); 
		      setRequired('PrimAdd'); 
		      setRequired('PrimCity'); 
		      //setRequired('State'); 
		      //setRequired('ZipCode'); 
		      setHiddenLandingScriptVal(popUrl); 
		      popupVisible = true;
		      jQuery('#form1 label').css('color', epOriginalLabelColor);
				}	
		  }
		 });
	  }
	});

	pageTracker._trackEvent("popup_div", "presented",  popUrl);  // Google's event tracker
	logExtra = popUrl;
	logEvent('PopUp Presented');
// TB  temp changes 3/242/010
	var cookieName = "popupPresentedCount";
	var cookieValue = getCookieValue(cookieName);
	if (cookieValue && cookieValue != "NaN") {
		cookieValue = cookieValue * 1;
		cookieValue += 1;
	}
	else {
		cookieValue = 1;
	}
	createCookie(cookieName, cookieValue, 365);
    createCookie('lastPopupDate', Date(), 365);
}

function dismissVideoRequest() {
	gPopupForm.close();
	popupVisible = false;
	var popUrl = getPopURL(false);
	pageTracker._trackEvent("popup_div", "dismissed",  popUrl);  // Google's event tracker
	logExtra = popUrl;
	logEvent('PopUp Dismissed');
}

//
//  Load in the form and return it as a string
//
function getPostArrayFromForm(FormID) {
    var myFormArray = new Array();
    myFormArray = Form.serialize(FormID);
    return myFormArray;
}

//
// Validate the form before submission
//
function epValidateForm(FormID) {
    var ret = true;
    var requiredFields = jQuery('#' + FormID + ' .form_required');
    var turnRed = false;
    var turnBlack = true;
    if (typeof epOriginalLabelColor != 'undefined') {
	
    }
    else {
	epOriginalLabelColor = jQuery('#form1 label').css('color');
    }
    //alert (epOriginalLabelColor);
    
    requiredFields.each(function(i, v) {
	
        switch (v.tagName) {
            case 'INPUT':
                if (v.value.trim() == '') {
                    ret = false;
		    turnRed = true;
		    turnBlack = false;
                    //jQuery('#' + v.id).parent().prev().css('color', '#FF0000');
		    
                }
                else {
		    turnRed = false;
		    turnBlack = true;
                    //jQuery('#' + v.id).parent().prev().css('color','#000000');
                }
                break;
            case 'SELECT':
                if (v.selectedIndex == 0) {
                    ret = false;
		    turnRed = true;
		    turnBlack = false;
                    //jQuery('#' + v.id).parent().prev().css('color', '#FF0000');
                }
                else {
		    turnRed = false;
		    turnBlack = true;
                    //jQuery('#' + v.id).parent().prev().css('color','#000000');
                }
                break;
        }
	if (turnRed) {
	    jQuery("label[for='" + v.id + "']").css('color', '#FF0000');
	    jQuery("#required_legend").show();
	    jQuery("#required_legend label").css('color', '#FF0000');
	}
	else if (turnBlack) {
	    jQuery("label[for='" + v.id + "']").css('color', epOriginalLabelColor);
	    jQuery("#required_legend").hide();
	}
    });
    
    if (!ret) {

	//var popUrl = getPopURL(false);
	pageTracker._trackEvent("popup_div", "bad submission",  popUrl);  // Google's event tracker
	logExtra = popUrl;
	logEvent('Form Submitted Bad');
    }
    return ret;
}

//
//  Handle the pop up form submit event with an ajax call
//
function postDataToServer(FormID) {
    if (epValidateForm(FormID)) {
        var postData = getPostArrayFromForm(FormID);
        var postURL = jQuery('#' + FormID)[0].action;
        jQuery.ajax({
            url: postURL,
            type:'POST',
            data: postData,
            dataType:'html',
            async:'false',
            timeOut:10000,
            success: function(html) {
		//var popUrl = getPopURL(false);
		popupVisible = false;
		pageTracker._trackEvent("popup_div", "good submission",  popUrl);  // Google's event tracker
		logExtra = popUrl;
		logEvent('Form Submitted Good');
		createCookie('formSubmissionDate', Date(), 365);
		gPopupForm.close();
		var currentPathName = location.pathname;
		if (currentPathName.charAt(0) == "/") {
		    currentPathName = currentPathName.slice(1);
		}
		location.href = '/f3.php?from=' + currentPathName;
            },
            error: function() {
            alert("We experienced an error sending your request, please try again.");
            }
        });
    }
}

//
// Functions for debugging -- not currently used
//
function parseLocation() {
  var epURL = location.href;
  var epURLFile = epURL.split('?')[0];
  var epURLQuery = epURL.split('?')[1];
  var epURLParts = new Array();

  if (typeof epURLQuery != 'undefined') {
    //alert (epURLQuery);
    var tempParts = epURLQuery.split('&');
    if (tempParts.length > 0) {
	var tempIndex = '';
	var tempVal = '';
	var tempArgs;
	for (var i = 0; i < tempParts.length; i ++) {
	    tempArgs = tempParts[i].split('=');
	    tempIndex = tempArgs[0];
	    tempVal = tempArgs[1];
	    epURLParts[tempIndex] = tempVal;
	}
    }
  }
  return(epURLParts);
}  

function getQueryVal(queryIndex) {
    var epURLParts = parseLocation();
    var retVal = false;
    if (typeof epURLParts[queryIndex] != 'undefined') {
	retVal = epURLParts[queryIndex];
    }
    return retVal;
}

//
//  Main
//

// Reset dismissal counts and click counts after 7 days, hold popups for 7days after form submission
checkPopUpCycle(); 

//  Set up the dismiss count logic
var presentedCounts = new Array();
presentedCounts[0] = 3;
presentedCounts[1] = 15;
presentedCounts[2] = 100;
presentedCounts[3] = 10000;
presentedCounts[4] = 1000000;

//  On Document Ready  -- DOM is loaded, page contents are not yet loaded
jQuery(document).ready(function() {
    //  Set up click counting by attaching an event listener to each link on the page
	  setupLinksForCounting();
    });
    
//  On Window Load -- page contents are loaded
jQuery(window).load(function () {
    
    // Just in case we need two modal windows - currently not used
	Window.keepMultiModalWindow = true;
	
    //  Decide if a click-based pop-up should be displayed	
	if (timeBasedPopup!="") {DontShowClickPopup = true;}

    // Check to see if B-pack pop up is appropriate
	var displayClickBasedPopup = false;	
	if (popupPresentedCount < 4) {
	  if (clickedCount >= presentedCounts[popupPresentedCount] && clickedCount < presentedCounts[popupPresentedCount + 1]) {
	    displayClickBasedPopup = !DontShowClickPopup && videoRequested == 'N';
	  }
	}

    // Check to see if D-pack pop up is appropriate
	var displayIdeaKitPopup = false;
	if (popupPresentedCount < 4) {
	    if (clickedCount >= presentedCounts[popupPresentedCount] && clickedCount < presentedCounts[popupPresentedCount + 1]) {
  	      displayIdeaKitPopup = !DontShowClickPopup && videoRequested == 'Y' && ideaKitRequested == 'N' && !in7dayhold; 
  	    }
  	  }

	if (displayClickBasedPopup) {
	    displayVideoRequest();
	}
	
	if (displayIdeaKitPopup) {
	    doideaKitPopup = true;
	    displayVideoRequest();
	}
	
	// Decide if a time-based pop-up should be displayed
	if (timeBasedPopup!="") {
	  if(videoRequested != 'Y') {
        if (popupPresentedCount == 0) setTimeout("displayVideoRequest()", timeBasedTimer1);  
        if (popupPresentedCount == 1) setTimeout("displayVideoRequest()", timeBasedTimer2);
        }
	  }
	
    });
 
 // Add a listener for the window unload event to track pop-up abandons
 jQuery(window).bind('beforeunload', function() {
	if (popupVisible) {
	    //var popUrl = getPopURL(false);
	    pageTracker._trackEvent("popup_div", "abandoned",  popUrl);  // Google's event tracker
	    //logExtra = popUrl;
	    //logEvent('PopUp Abandoned');

	    //Dialog.closeInfo();	
	    gPopupForm.close();
	    popupVisible = false;
	}
    });
 
 function displayEmailPopup() {
	var emailURL = '/all/referral_popup.html';
	//gPopupForm = Dialog.info(emailURL, { windowParameters: {id:"gPopupForm", resizable: false, width: 500, height:450, destroyOnClose: true}});
	jQuery.ajax({
	    url: emailURL,
	    type:'GET',
	    dataType:'html',
	    async:'false',
	    timeOut:10000,
	    success: function(html) {
		gPopupForm = Dialog.info(html, { windowParameters: {id:"gPopupForm", resizable: false, width: 562, top: 15, destroyOnClose: true, onShow: function() {defaultify(".default-value");}}});
		//gPopupForm = new Window({width:800, height:450, resizable: false, recenterAuto: true, destroyOnClose: false, draggable:false, wiredDrag: false, maximizable:false, minimizable:false, closable:false});
		//gPopupForm.setZIndex(2000);
		//gPopupForm.getContent().innerHTML=html;
		//gPopupForm.toFront();
		//gPopupForm.setDestroyOnClose();
		//gPopupForm.showCenter(true);
		//setRequired('FirstConTitle'); setRequired('ContactFirst'); setRequired('ContactLast'); setRequired('PrimAdd'); setRequired('PrimCity'); setRequired('State'); setRequired('ZipCode');
	    },
	    error: function() {
		
	    },
	    complete: function() {
		
	    }
	});
}

        
        var active_color = '#000'; // Colour of user provided text
        var inactive_color = '#999'; // Colour of default text
        var default_values = new Array();
        
        function defaultify(s) {
			
            jQuery(s).css("color", inactive_color);
			
			jQuery(s).each(function(index, element) {
				if (!default_values[this.id]) {
                    default_values[this.id] = this.value;
                }
			});
			
            jQuery(s).focus(function() {
                if (!default_values[this.id]) {
                    default_values[this.id] = this.value;
                }
                if (this.value == default_values[this.id]) {
                    this.value = '';
                    this.style.color = active_color;
                }
                jQuery(this).blur(function() {
                    if (this.value == '') {
                        this.style.color = inactive_color;
                        this.value = default_values[this.id];
                    }
                });
            });
        }
        
        function addRecipient() {
            var currentCount = jQuery('#to_div input').length;
            jQuery('#to_div').append('<div class="inputWrapper"><input type="text" class="inputFriendEmail default_value" id="email_to_' + currentCount + '" name="email_to[]" value="Friend\'s Email" /> <span class="control_button" onclick="javascript:addRecipient();"><img src="/images/referafriend/button_addrecipient.png"></span>  <span class="control_button" onclick="javascript:deleteRecipient(event);"><img src="/images/referafriend/button_delrecipient.png"></span></div>');
            defaultify('#email_to_' + currentCount);
        }
        function deleteRecipient(event) {
            var subtracter = jQuery(event.currentTarget);
            var adder = subtracter.prev();
            var einput = adder.prev();
            var linebreak = subtracter.next();
			var parentDiv =einput.parent();
            subtracter.remove();
            adder.remove();
            einput.remove();
            linebreak.remove();
			parentDiv.remove();
        }
		
		function submit_friend_email() {
			var formOk = check_email_form();
			var goodFrom = check_email_address(jQuery('#email_from').val());
			var goodTo = true;
			jQuery('input[name="email_to[]"]').each(function(index, element) {
				if (check_email_address(element.value)) {
					// still good
				}
				else {
					goodTo = false;
					// maybe 
				}
			});
			if (formOk) {
				
			}
			else {
				alert ("All fields must be completed in order to send email.");
			}
			if (formOk && goodFrom && goodTo) {
				var email_query_string = jQuery('#email_form').serialize();
				var currentURL = location.href;
				var emailURL = '/all/friend_email.php?' + email_query_string + '&URL=' + currentURL;
				jQuery.ajax({
					url: emailURL,
					type:'GET',
					dataType:'json',
					async:'false',
					timeOut:10000,
					success: function(json) {
						logExtra = email_query_string;
						logEvent('Tell A Friend');
					},
					error: function() {
					
					},
					complete: function() {
						Dialog.closeInfo();
					}
				});
			}
			else {
				
			}
		}
		
		function check_email_form() {
			var ret = true;
			jQuery('#email_form .default-value').each(function(index, element) {
				//alert (element.value);
				if (element.value == default_values[element.id]) {
					ret = false;
				}
			});
			return ret;
		}
		
		function check_email_address(address) {
			var ret = true;
			if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(address)){
				ret = true;
			}
			else {
				alert("Invalid E-mail Address! Please re-enter.")
				ret = false;
			}
			return ret;
		}
 
/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function bookmarksite(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "");
logEvent('Page Bookmarked');
}

