$(document).ready(function(){
    // Select correct tab
    var activeTabId = $("#activeTabId").val();

    if(window.location.pathname == '/pages/how-it-works') {
        activeTabId = 'howItWorksTab';
    }

    if($("#expiredLabel").length == 1) {
        activeTabId = '';
    }

    var activeTab = $('#' + activeTabId);

    if(activeTab.length == 1) {
        var imageSrc = activeTab.find('img').attr('src');

        activeTab.find('img').attr('src', imageSrc.replace('.png', '-down.png'));
    }

    var urlParts = window.location.href.split('/');
    var baseUrl = urlParts[urlParts.length - 1];
    var email = getParameterByName('rcpEmail');
    var utmSource = getParameterByName('utm_source');

    // If they came from an email or aDealio, hide the lightbox and set a cookie
    if(email != '' || utmSource == 'aDealio') {
        hideLightbox = true;
        createCookie('hideLightbox', 1, 30);
    } else {
        hideLightbox = readCookie('hideLightbox');
    }

    // Try to get utmSource from params, if not there try cookies
    if(utmSource != '') {
        createCookie('utmSource', utmSource, 30);
    } else {
        utmSource = readCookie('utmSource');
    }

    // Set the utm_source on any signup forms we've created (lightbox)
    $("input[name=campaignSrc]").val(utmSource);

    // Show subscribe widgets if not logged in and not on subscribe, unsubscribe, login page and not coming from email
    var showSubscribeWidgets = accountVisible == 'none' &&
                               window.location.pathname != '/pages/subscribe' &&
                               window.location.pathname != '/pages/privacy' &&
                               window.location.pathname != '/login' &&
                               window.location.pathname != '/alertsUnSubscribe.action';

    if(showSubscribeWidgets) {
        subscribeWidget = $("#sidenav-signup");

        if(utmSource != '') {
            iframeSrc = subscribeWidget.attr('src');
            subscribeWidget.attr('src', iframeSrc + '?campaignSrc=' + utmSource);
        }

        subscribeWidget.show();
    }

    if(showSubscribeWidgets && hideLightbox == null) {
        $("#splash").dialog({modal: true,
                             draggable: false,
                             resizable: false,
                             width: '695'
                            });

        // If they close the lightbox, hide it for the rest of their session
        $("#splash").bind( "dialogbeforeclose", function(event, ui) {
            createCookie('hideLightbox', 1, false);
        });
    }

    $("#email").focus(function() {
        if($(this).val() == 'Enter your email address') {
            $(this).val('');
        }
    });

    $("#email").blur(function() {
        if($(this).val() == '') {
            $(this).val('Enter your email address');
        }
    });

    var formOptions = {
        success: function(response) { showResponse(response, 'lightbox'); },
        dataType: 'json'
    }

    $("#lightbox-subscribe").ajaxForm(formOptions);

    // Add timestamp to other-deals widget to ensure we don't get a cached version
    $("#other-deals-small").attr('src', $("#other-deals-small").attr('src') + '?' + new Date().getTime());

    // Add products iframe
    $(".dealFullInfo").append('<iframe src="//external.dailydeals.com/widget/products/base_url/' + baseUrl + '" height="475" width="718" scrolling="no" frameborder="0" id="products"></iframe>');

    // Add facebook comments
    html = '<div id="fb-root"></div>' +
           '<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>' +
           '<div id="comments"><fb:comments href="http://www.dailydeals.com' + window.location.pathname + '" num_posts="5" width="698"></fb:comments></div>';
           //'<div id="comments"><fb:comments href="http://stage.dailydeals.com" num_posts="5" width="698"></fb:comments></div>';

    $(".dealFullInfo").append(html);
});

function getParameterByName(name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);

    if(results == null) {
        return "";
    } else {
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
}

function showResponse(response, source)
{
    if(response.success) {
        $("#subscribe-form").after('<p class="success">Thanks for signing up!</p><p>Please check your inbox/spam folder for our welcome email and <a href="/whitelist">whitelist us</a> to never miss a deal</p>').remove();

        // Close lightbox
        window.setTimeout(function() { $("#splash").dialog("destroy"); }, 6000);

        // Push the google analytics email subscribe event
        _gaq.push(['_trackEvent', 'email', 'subscribe', source]);

        // Prevent lightbox from opening on subsequent pages
        createCookie('hideLightbox', 1, 30);
    } else {
        $("p.error").html(response.message).show();
    }
}

function createCookie(name,value,days)
{
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
        var expires = "";
    }

	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0; i < ca.length; i++) {
		var c = ca[i];

		while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }

		if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
	}
    
	return null;
}
