$(document).ready(function(){
/* this is where the magic happens.. */
    $('#mycarousel').jcarousel();  

    var email = $("#email");
    var allFields = $([]).add(email);
    var tips = $("#validateTips");
    var newsletterEmail = $('#newsletterEmail');

    var topBannerHeight = 159;
	var bottomCarouselHeight = 111;
	
	var heightOfFrame = $(window).height() - (topBannerHeight + bottomCarouselHeight);
	
	$(window).resize(function(){
	    heightOfFrame = $(window).height() - (topBannerHeight + bottomCarouselHeight);
	
	    $('#theVoucher').css('height', heightOfFrame);
	    $('#theFrame').css('height', heightOfFrame);
	    $('#TB_overlay').css('height', heightOfFrame);
    });
	
	$('#theVoucher').css('height', heightOfFrame);
	$('#theFrame').css('height', heightOfFrame);
	$('#TB_overlay').css('height', heightOfFrame);

    $("#newsletterEmail").keypress(function (e) {
          if (e.which == 13) {
              $("#newsletter_btn").trigger('click');
              return false;
          }
    });

	if (typeof(disableEmailGrabber) != 'undefined') {
	    if (disableEmailGrabber == 1) {
			trackConv(3);
			$('.newsletter').hide();
			$('#TB_overlay').hide();
			$('#TB_window').hide();

			/* this seems silly, but it's the only way to get it to work in FF */
			var originalSource = $('#theVoucher').attr('src');
			$('#theVoucher').attr('src', '');
			$('#theFrame').show();
			$('#theFrame').css('visibility', 'visible');
			$('#theVoucher').attr('src', originalSource);
		}
	}
	
    if ($.cookie('PrintableVouchers') == '1') {
	    trackConv(3);
        $('.newsletter').hide();
        $('#TB_overlay').hide();
        $('#TB_window').hide();

        /* this seems silly, but it's the only way to get it to work in FF */
        var originalSource = $('#theVoucher').attr('src');
        $('#theVoucher').attr('src', '');
        $('#theFrame').show();
		$('#theFrame').css('visibility', 'visible');
        $('#theVoucher').attr('src', originalSource);
    }

    function updateTips(t) {
        tips.text(t).effect("highlight", {}, 1500);
    }

    function checkLength(o,n,min,max) {

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between "+min+" and "+max+".");
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o,regexp,n) {
        if (! regexp.test(o.val()) ) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    $("#invalid").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 140,
        modal: true, 					
		buttons: {
			"OK": function() { 
				$(this).dialog("close"); 
			}
		}
    });

    $("#waitingConfirmation").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 170,
        modal: true
    });

    $("#dialog").dialog({
        position: 'top',
        bgiframe: true,
        autoOpen: false,
        height: 100,
        modal: true,
        buttons: {
            'SIGNUP': function() {
                var bValid = true;
                allFields.removeClass('ui-state-error');

                bValid = bValid && checkLength(email,"email",6,80);
                bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. lucy1982@hotmail.co.uk");

                if (bValid) {
                    var dataString = 'emailiFrame='+ $('#email').val() + '&voucherID=' + printableVoucherID; 
                    $.ajax({  
                        type: "POST",  
                        url: "http://www.discountvouchers.co.uk/wp-content/themes/New-DV2/signup.php",  
                        data: dataString
                    }); 

                    $(this).dialog('close');
                }
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            allFields.val('').removeClass('ui-state-error');
        }
    });

    $('#newsletterLink').click(function() {
        $('#dialog').dialog('open');
        return(false);
    });

    function getCookie(c_name)
	{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
	}

	
    $('#newsletter_btn').click(
        function() {
            var formEmail = $('#newsletterEmail').val();
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

			// Invalid e-mail
            if (!filter.test(formEmail)) {
                $("#invalid").dialog('open');
			// Valid e-mail, so show confirmation dialog box
            } else {
			    /* google conversion: user has given a valid e-mail */
				trackConv(1);
				
				/* show waiting for confirmation dialog */
				$("#waitingConfirmation").dialog('open');

				/* get rid of the ajax loading icon after 10 seconds */
				setTimeout("activateButton()", 10000);

				/* add e-mail to database */
				var dataString = 'emailiFrame='+ $('#newsletterEmail').val() + '&voucherID=' + printableVoucherID; 
				$.ajax({  
					type: "POST",  
					url: "http://www.discountvouchers.co.uk/wp-content/themes/New-DV2/signup.php",  
					data:({
						  emailiFrame : $('#newsletterEmail').val(),
					  	  email_source: $('#email_source').val(),
					      entry_keyword: getCookie('LocalSearch'),
					      voucher_id: printableVoucherID
						  })
				});
				
				var dataString = 'http://www.discountvouchers.co.uk/wp-content/themes/New-DV2/signup.php?' + 'emailiFrame=' + $('#newsletterEmail').val() + '&voucherID=' + printableVoucherID; 

				 $.ajax({
				   type: "GET",
				   url: dataString,
				   success: function(data){
					/* e-mail has not been confirmed, LIARS! */
					if (data == 1) {
					   /* track this as a confirmation, for Doug */
					   trackConv(3);
					   
					   /* drop a cookie so they don't get this prompt for 20 days */
					   $.cookie("PrintableVouchers", "1", { expires: 20 });

					   /* SHOW PAGE :) */
					   $('.newsletter').hide();
					   $('#TB_overlay').hide();
					   $('#TB_window').hide();
					   $("#waitingConfirmation").dialog('close');

					   /* this seems silly, but it's the only way to get it to work in FF */
						var originalSource = $('#theVoucher').attr('src'); 
						$('#theVoucher').attr('src', ''); 
						$('#theFrame').show(); 
						$('#theFrame').css('visibility', 'visible');
						$('#theVoucher').attr('src', originalSource);
					}
				 }});
            }

            return(false);
        }
    );
	
	/* how many times has the user clicked the confirm button? */
	var buttonClickCount = 0;
	
	$('#confirmationButton').click(function(){
	    /* if they've clicked the button unsuccessfully more than 10 times, forget doing another ajax call */
	    if (buttonClickCount > 10) {
		    return false;
		}
	
		var dataString = 'http://www.discountvouchers.co.uk/wp-content/themes/New-DV2/signup.php?' + 'emailiFrame=' + $('#newsletterEmail').val() + '&voucherID=' + printableVoucherID; 

		 $.ajax({
		   type: "GET",
		   url: dataString,
		   success: function(data){
			/* e-mail has not been confirmed, LIARS! */
			if (data != 1) {
				alert("E-mail address not confirmed, please check your inbox and spam folders again.");
				buttonClickCount++;
			/* e-mail was confirmed */
			} else {
			   /* track this as a confirmation, for Doug :) */
			   trackConv(3);
			   
			   /* drop a cookie so they don't get this prompt for 20 days */
			   $.cookie("PrintableVouchers", "1", { expires: 20 });

			   /* SHOW PAGE :) */
			   $('.newsletter').hide();
			   $('#TB_overlay').hide();
			   $('#TB_window').hide();
			   $("#waitingConfirmation").dialog('close');

			   /* this seems silly, but it's the only way to get it to work in FF */
				var originalSource = $('#theVoucher').attr('src'); 
				$('#theVoucher').attr('src', ''); 
				$('#theFrame').show(); 
				$('#theFrame').css('visibility', 'visible');
				$('#theVoucher').attr('src', originalSource);
			}
		 }});

	     return false;
	});
});

function blank(a) { if(a.value == a.defaultValue) a.value = ""; }
function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
function activateButton() {$('#loadingIcon').hide();$('#confirmationButton').show();}

function trackConv(conversionAction) {
    var google_conversion_id = 1041045776;
    var google_conversion_language = "en_GB";
    var google_conversion_format = "3";
    var google_conversion_color = "ffffff";

	switch (conversionAction) {
	    /* email given */
	    case 1:
            var google_conversion_label = "xZd3CKThmQEQkLK08AM";
		    break;
		/* landed on confirmation page */
		case 2:
            var google_conversion_label = "WyR9CKCHmgEQkLK08AM";
		    break;
		/* confirmation button clicked, confirmed */
		case 3:
            var google_conversion_label = "DarkCP7hmQEQkLK08AM";
		    break;
		/* confirmed and saved personal details */
		case 4:
            var google_conversion_label = "8jnQCNjimQEQkLK08AM";
		    break;
		/* test for GraphicMail tracking */
		case 666:
		    var google_conversion_label = "FElcCMrBmwEQkLK08AM";
		    break;
	}

    var iframeURL = "http://www.discountvouchers.co.uk/AdWordsTracker.php?conversionID=" + google_conversion_id + "&conversionLabel=" + google_conversion_label;
	$('#adwordsTracking').attr('src', iframeURL);
    return;
}

