﻿var deviceId = null, ci_CheckInstall_Return = null, ci_CheckPrinter_Return = null, ci_InstallPrinter_Return = null;

function HideHowItWorks(timeSpan) {
    jQuery("#howItWorks").slideUp(timeSpan);
    jQuery("#welcomeLearnMore").show();
}

function ShowHowItWorks() {
    jQuery("#howItWorks").slideDown(500);
    jQuery("#welcomeLearnMore").hide();
}

function roundNumber(num) {
    return Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);
}

function printResponse(responseCode, responseTitle, responseMessage) {
    $('#PrinterResponseText').html(responseTitle);
    $('#PrinterResponseDesc').html(responseMessage);
    $("#CouponPrintMessageLink").click();
}

var emailedcouponid = "";

jQuery(document).ready(function () {
    $("#CouponPrintMessageLink").colorbox({ opacity: 0.5, width: "400px", inline: true, href: "#CouponPrintMessage" });
    $("#CouponInstallPrinterLink").colorbox({ opacity: 0.5, width: "400px", inline: true, href: "#CouponInstallPrinter" });
    $("#CheckCouponsToPrintMessageLink").colorbox({ opacity: 0.5, width: "400px", inline: true, href: "#CheckCouponsToPrintMessage" });
    $("#InstallProcessCompleteLink").colorbox({ opacity: 0.5, width: "400px", inline: true, href: "#InstallProcessComplete" });
    $("#EmailDialogLink").colorbox({ opacity: 0.5, width: "415px", inline: true, href: "#EmailDialogPopup" });
    $("#SharedCouponDisplayLink").colorbox({ opacity: 0.5, width: "400px", inline: true, href: "#SharedCouponDisplay" });

    $(document).bind('cbox_closed', function () {
        if ($($.fn.colorbox.element()).attr('id').match('InstallProcessCompleteLink')) {
            InstallProcessCompleteOkButtonClick();
        }
        else if ($($.fn.colorbox.element()).attr('id').match('CouponPrintMessageLink')) {
            location.replace(location.href.replace(location.search, ""));
        }
    });

    var bannerArea = $('#bannerAds');
    var tabsArea = $('#tabs');
    var coupons = $('.couponDisplayWidth');
    var sharedCouponId = getParameterByName("couponid");

    jQuery(".couponCheckBoxControl input").click(function () {
        var savedAmount = 0;
        var numberClipped = 0;

        // adjust coupon for selected coupon and non-selected
        $(this).parents('#CouponContainer').toggleClass('selectedCoupon');

        if ($(this).attr('checked')) {
            $(this).parents('.couponCheckBoxContainer').find('#couponClipImg').attr('src', '/Images/coupons_remove.png');
        } else {
            $(this).parents('.couponCheckBoxContainer').find('#couponClipImg').attr('src', '/Images/coupons_clip.png');
        }

        jQuery(".couponCheckBoxControl input:checked").each(function (i, object) {
            savedAmount = savedAmount + roundNumber(parseFloat(jQuery(this).attr("couponvalue")));
            numberClipped++;
        });

        jQuery(".moneySavedValue").html(savedAmount.toFixed(2));
        jQuery(".couponsClippedValue").html(numberClipped);
    });

    if (tabsArea && tabsArea.length > 0) {
        tabsArea.tabs();
    }

    if (bannerArea && bannerArea.length == 0) {
        coupons.css("width", "100%");
    }

    // if on print coupons page, set the device id
    if ($('#printCoupons').length > 0) {
        // select any attempted coupons user wanted printed before having to install the printer
        var selectedCoupons = $.cookie('EDS_CouponsAttemptedToPrint');
        if (selectedCoupons != null && selectedCoupons.length > 0) {
            var couponsArr = [];
            couponsArr = selectedCoupons.split(',');
            for (var i = 0; i < couponsArr.length; i++) {
                $(".couponCheckBoxControl input[couponid=" + couponsArr[i] + "]").attr('checked', 'checked');
                $(".couponCheckBoxControl input[couponid=" + couponsArr[i] + "]").trigger('click');
                $(".couponCheckBoxControl input[couponid=" + couponsArr[i] + "]").attr('checked', 'checked'); // hack as it deselects the checkbox
            }

            $.cookie('EDS_CouponsAttemptedToPrint', '');
        }

        ci_CheckInstall_Return = initDisplay;
        try {
            ci_CheckInstall();
        } catch (err) {
            // handle?
        }
    }

    if (sharedCouponId && sharedCouponId.length > 0) {
        $("#SharedCouponDisplayLink").click();

        if (deviceId) {
            $('#SharedCouponPrint').show();
        } else {
            $('#SharedCouponPrint').hide();
        }
    }

    $('.couponButton').click(function (e) {
        e.preventDefault();

        $("#SharedCouponDisplayLink").colorbox.close();

        var checkbox = $(".couponCheckBoxControl input[couponid=" + getParameterByName("couponid") + "]");
        checkbox.click();
        checkbox.attr('checked', 'checked');
        checkbox.parents('.couponCheckBoxContainer').find('#couponClipImg').attr('src', '/Images/coupons_remove.png');

        if ($(this).attr('printCoupon') === 'true') {
            setTimeout("$('#topPrintableCouponLink').click()", 500);
        }
    });

    if ($('#sponsorLogoList li').length > 1) {
        var autoValue = $('#sponsorLogoList li').length > 6 ? 1000 : null;
        $('#SponsorLogoTray .jCarouselLite').jCarouselLite({
            auto: autoValue,
            speed: 5000,
            visible: 6
        });
    }

    $(".couponEmailLink").click(function () {
        emailedcouponid = $(this).attr("couponid");
        OpenEmailPopup();
    });

    $("#HowItWorksLearnMore").mouseover(function () {
        $("#CouponPrinterInfoDiv").css("top", $("#HowItWorksLearnMore").position().top + 20);
        $("#CouponPrinterInfoDiv").css("left", $("#HowItWorksLearnMore").position().left - 300);
        $("#CouponPrinterInfoDiv").slideDown(500);
    });

    jQuery("#HowItWorksLearnMore").mouseout(function () {
        jQuery("#CouponPrinterInfoDiv").slideUp(500);
    });

    jQuery(".couponCheckBoxControl input").click(function () {
        var savedAmount = 0;
        var numberClipped = 0;

        // adjust coupon for selected coupon and non-selected
        $(this).parents('#CouponContainer').toggleClass('selectedCoupon');
        $(this).parents('#CouponContainer').find('div:first').toggleClass('selectedCoupon'); // For IE 8

        if ($(this).attr('checked')) {
            $(this).parents('.couponCheckBoxContainer').find('#couponClipImg').attr('src', '/Images/coupons_remove.png');
        } else {
            $(this).parents('.couponCheckBoxContainer').find('#couponClipImg').attr('src', '/Images/coupons_clip.png');
        }

        jQuery(".couponCheckBoxControl input:checked").each(function (i, object) {
            savedAmount = savedAmount + roundNumber(parseFloat(jQuery(this).attr("couponvalue")));
            numberClipped++;
        });

        jQuery(".moneySavedValue").html(savedAmount.toFixed(2));
        jQuery(".couponsClippedValue").html(numberClipped);
    });

    $('.printCouponLink').click(function (e) {
        e.preventDefault();
        var selectedCouponIds = [];

        $('.couponCheckBoxControl input:checked').each(function (i, obj) {
            if ($.inArray($(this).attr('couponid'), selectedCouponIds) === -1) {
                selectedCouponIds.push($(this).attr('couponid'));
            }
        });

        if (selectedCouponIds.length > 0) {
            if (deviceId) {
                $.ajax({
                    url: "/services/CouponService.asmx/PrintCoupons",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: '{ deviceId:' + deviceId + ', checkedArr: \'' + selectedCouponIds + '\'}',
                    success: function (msg) {
                        $('#printCouponsIframe').attr('src', msg.d);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(textStatus + ': ' + errorThrown);
                    }
                });
            }
            else {
                $.cookie('EDS_CouponsAttemptedToPrint', selectedCouponIds);
                $("#CouponInstallPrinterLink").click();
            }
        } else {
            $('#CheckCouponsToPrintMessageLink').click();
        }

    });

    $('#displayPrintableFAQ').click(function (e) {
        e.preventDefault();
        $('#FAQPrintableTab').click();
        $('#tabs').scrollTop();
    });

    $('.couponSortLink').click(function (e) {
        e.preventDefault();

        var sortAttributeName = $(this).attr('sortAttrName');
        var sortedInactiveArray = [];
        var sortedActiveArray = [];

        $('#printCouponsDisplay #HasCoupons > [' + sortAttributeName + ']').each(function (i) {
            var value = $(this).attr(sortAttributeName);
            var active = $(this).attr("active");

            if (active == "true") {
                if ($.inArray(value, sortedActiveArray) == -1) {
                    sortedActiveArray.push(value);
                }
            }
            else if (active == "false") {
                if ($.inArray(value, sortedInactiveArray) == -1) {
                    sortedInactiveArray.push(value);
                }
            }
        });

        sortedActiveArray.sort();
        sortedInactiveArray.sort();

        var activeDivs = $(sortedActiveArray).map(function (index, data) {
            return $('#printCouponsDisplay #HasCoupons > [' + sortAttributeName + '="' + data + '"]').get();
        });

        var inactiveDivs = $(sortedInactiveArray).map(function (index, data) {
            return $('#printCouponsDisplay #HasCoupons > [' + sortAttributeName + '="' + data + '"]').get();
        });

        $('#printCouponsDisplay #HasCoupons').empty().append(activeDivs).append(inactiveDivs);
    });

    if ($("html").hasClass("ie7")) { // Hack for ie7 to get featured coupons to show. Otherwise they hide behind the background image.        
        $("#featuredCoupons").toggleClass("featuredCoupons");
        setTimeout("$('#featuredCoupons').toggleClass('featuredCoupons');", 50);
    }
});

function OpenEmailPopup() {
    $('#emailErrors').valueOf(' ').hide();
    $('#EmailDialogLink').click();
}

function isEmail(value) {
    value = jQuery.trim(value);
    return /^((([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.test(value);
}

function SendEmail() {
    //var isValid = ValidateEmailForm();
    var results = validateEmailForm();

    $('#emailErrors').val('&nbsp;').hide();


    if (results.valid) {
        var url;
        var data;

        if (emailedcouponid != undefined && emailedcouponid.length > 0) {
            url = "/services/EmailService.asmx/SendCouponEmail";
            data = '{campaignIdString: \'' + $("#CampaignIdHiddenField").val() + '\', toEmail: \'' + $("#ToEmailAddressTextBox").val() + '\', fromFirstName: \'' + $("#YourFirstNameTextBox").val() + '\', fromLastName: \'' + $("#YourLastNameTextBox").val() + '\', fromEmail: \'' + $("#YourEmailAddressTextBox").val() + '\', sendCopy:' + $("#SendACopyCheckBox").attr("checked") + ', couponId:\'' + emailedcouponid + '\'}';
        }
        else {
            url = "/services/EmailService.asmx/SendSiteEmail";
            data = '{campaignIdString: \'' + $("#CampaignIdHiddenField").val() + '\', toEmail: \'' + $("#ToEmailAddressTextBox").val() + '\', fromFirstName: \'' + $("#YourFirstNameTextBox").val() + '\', fromLastName: \'' + $("#YourLastNameTextBox").val() + '\', fromEmail: \'' + $("#YourEmailAddressTextBox").val() + '\', sendCopy:' + $("#SendACopyCheckBox").attr("checked") + '}';
        }

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: data,
            success: function (msg) {
                if (msg.d) {
                    CloseEmail();
                    $('#EmailDialogPopup > input').val('');
                }
                else {
                    $('#emailErrors').show().html('Unable to send the email at this time. Please try again in a little while.');
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ': ' + errorThrown);
            }
        });
    } else {
        $('#emailErrors').show().html('Errors:<br/><ol>' + results.errorMsg + '</ol>');
    }
}

function InstallProcessCompleteOkButtonClick() {
    $('#InstallProcessComplete').colorbox.close();
    location.reload(true);
}

function OpenInstallProcessComplete() {
    $("#CouponInstallPrinterLink").colorbox.close();
    setTimeout("$('#InstallProcessCompleteLink').click()", 500);
}

function CloseEmail() {
    $('#EmailDialogLink').colorbox.close();
    emailedcouponid = "";
}

function validateEmailForm() {
    var isValid = true;
    var errors = '';

    if ($('#ToEmailAddressTextBox').val().length == 0) {
        isValid = false;
        errors += "<li>must provide an email address to send the email to.</li>";
    } else {
        var emails = $('#ToEmailAddressTextBox').val().split(',');

        for (var i = 0; i < emails.length; i++) {
            if (!isEmail(emails[i])) {
                isValid = false;
                errors += "<li>Email addresses to send to must be valid.</li>";
                break;
            }
        }
    }
    if ($('#YourFirstNameTextBox').val().length == 0) {
        isValid = false;
        errors += "<li>Your first name is required.</li>";
    }
    if ($('#YourLastNameTextBox').val().length == 0) {
        isValid = false;
        errors += "<li>Your last name is required.</li>";
    }
    if ($('#YourEmailAddressTextBox').val().length == 0) {
        isValid = false;
        errors += "<li>Your email is required.</li>";
    } else if (!isEmail($('#YourEmailAddressTextBox').val())) {
        isValid = false;
        errors += "<li>Your email address must be valid.</li>";
    }

    return { valid: isValid, errorMsg: errors };
}

/**/
function initDisplay(ci_vUserCode) {
    deviceId = ci_vUserCode;

    $.cookie('EDS_PrinterDevice', deviceId, { expires: 2000 });
}

function installPrinter() {
    try { ci_downloadFFSilent(); }
    catch (err) { }
}
/**/

window.log = function () {
    log.history = log.history || [];
    log.history.push(arguments);
    arguments.callee = arguments.callee.caller;
    if (this.console) console.log(Array.prototype.slice.call(arguments));
};
(function (b) { function c() { } for (var d = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","), a; a = d.pop(); ) b[a] = b[a] || c })(window.console = window.console || {});


function shareFacebook(sTitle, sOverrideURL) {
    var d;
    var l;
    var ou;
    var f = 'http://www.facebook.com/share';

    var e = encodeURIComponent;
    var p;

    if (sOverrideURL === '') {
        d = document;
        l = d.location;
        p = '.php?src=bm&v=3&u=' + e(l.href) + '&t=' + e(sTitle);
    } else {
        p = '.php?src=bm&v=3&u=' + e(sOverrideURL) + '&t=' + e(sTitle);
    }

    a = function () {
        if (!window.open(f + 'r' + p, 'sharer', 'toolbar=0, status=0, resizable=0, width=626, height=436'))

            l.href = f + p;
    };

    if (/Firefox/.test(navigator.userAgent)) {
        setTimeout(a, 0);
    } else {
        a();
    }

    void (0);
}

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, " "));
}

