﻿//framepopper
if (top.frames.length != 0) {
    if (self.document.location.href.indexOf('win-software') == -1 && self.document.location.href.indexOf('loginBox') == -1 && self.document.location.href.indexOf('remoteLogin') == -1) {
        top.location = self.document.location;
    }
}

//proxy fix
if (document.location.href.toLowerCase().indexOf('bitsdujour.com') == -1 && document.location.href.toLowerCase().indexOf('127.0.0') == -1 && document.location.href.toLowerCase().indexOf('cloudapp.net') == -1) {
    //document.location.href = 'http://www.bitsdujour.com';
}


//fix array indexOf
if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

var ajaxpath = '/ajax/';        //prod
//var ajaxpath = 'ajax/';             //dev

function now() {
    return (new Date).getTime();
}
//animate memory hog fix
jQuery.fx.prototype.custom = function(from, to, unit) {
    this.startTime = now();
    this.start = from;
    this.end = to;
    this.unit = unit || this.unit || "px";
    this.now = this.start;
    this.pos = this.state = 0;
    var self = this;
    function t(gotoEnd) {
        return self.step(gotoEnd);
    }
    t.elem = this.elem;
    if (t() && jQuery.timers.push(t) && !jQuery.fx.prototype.timerId) {
        jQuery.fx.prototype.timerId = setInterval(jQuery.fx.tick, 75);
    }
}


jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({ opacity: 'toggle' }, speed, easing, callback);
};


//price/discount counter
function mod(selector, delta, time, targetVal, up, decimals, prefix) {
    var $selector = $(selector);
    var numb = Number($selector.text().replace(prefix, ''));
    numb = numb + delta;
    $selector.text(prefix + numb.toFixed(decimals));
    if ((up && numb < targetVal) || (!up && numb > targetVal)) {
        setTimeout('mod("' + selector + '",' + delta + ',' + time + ',' + targetVal + ',' + up + ',' + decimals + ',"' + prefix + '")', time);
    } else {
        $selector.text(prefix + targetVal.toFixed(decimals));
        dupePrice(selector);
    }
}

var dupePriceCount = 0
function dupePrice(selector) {
    var box = $(selector).parents('.dealBoxNumbers');
    var boxid = '#' + box.attr('id') + ' ';
    dupePriceCount++;
    if (dupePriceCount%2 == 0) {
        var ins1 = box.clone().addClass('dealBoxNumbers1').attr('id', '').css({ 'opacity': 0.75 });
        var ins2 = box.clone().addClass('dealBoxNumbers2').attr('id', '').css({ 'opacity': 0.75 });
        var ins3 = box.clone().addClass('dealBoxNumbers3').attr('id', '').css({ 'opacity': 0.75 });
        var ins4 = box.clone().addClass('dealBoxNumbers4').attr('id', '').css({ 'opacity': 0.75 });
        ins1.insertBefore(boxid);
        ins2.insertBefore(boxid);
        ins3.insertBefore(boxid);
        ins4.insertBefore(boxid);
    }
}

function styleSweeps() {
    if (top.frames.length != 0) {
        if (self.document.location.href.indexOf('win-software') > -1) {
            $('.sweepIn').css({ 'width': '465px' });
            $('.sweepOut').css({ 'background': 'none' });
            $('.sweepNote').css({ 'margin': '10px 0 0 -11px', 'font-size': '18px' });
            $('.sweepFade').css({ 'display': 'none' });
            $('.sweepLogo').css({ 'display': 'none' });
            $('.sweepPanel').css({ 'margin': '92px 0 0 6px' });
            $('.sweepLeft').css({ 'margin': '419px 0 0 36px' });
            $('.sweepLegal').css({ 'margin': '1190px 0 0 30px' });
            $('.bdjAdminBar').css({ 'display': 'none' });
            $('.sweepPage').css({ 'background-color': 'transparent' });
            $('.sweepTagButtons').css({ 'margin': '-75px 0 0 295px', 'width': '150px' });
        }
    }
}

jQuery(document).ready(function ($) {

    styleSweeps();

    //move star up to header for SEO
    $('.bdjStar').hide().prependTo('.bdjTopIn').slideDown('slow');

    var Apple = {};
    Apple.UA = navigator.userAgent;
    Apple.Device = false;
    Apple.Types = ["iPhone", "iPod", "iPad"];
    for (var d = 0; d < Apple.Types.length; d++) {
        var t = Apple.Types[d];
        Apple[t] = !!Apple.UA.match(new RegExp(t, "i"));
        Apple.Device = Apple.Device || Apple[t];
    }

    //IE6 and iPhone floaty footer fix
    if (Apple.Device) {
        $('input.dealNewsletterEmail').css({ 'width': '120px' });
        $('div.dealFloatyFoot').css({ 'top': '0' });
        $('body:has(div.dealFloatyFoot)').css({ 'margin-top': '30px' });
    }

    //fix height of main area with overlapping right margin
    if ($('.dealRight').height() + 200 > $('.dealContrast').height() + $('.dealOne').height()) {
        $('.dealContrast').css('min-height', ($('.dealRight').height() - $('.dealOne').height() + 200) + 'px');
    }

    $('.countdown').countDown();

    $('.dealBoxNumbers').each(function (index) {
        var boxid = '#' + $(this).attr('id') + ' ';
        var percent = Number($(boxid + '.dealBoxSubPercent').text());
        if (!isNaN(percent)) {
            $(boxid + '.dealBoxSubPercent').text('0');
            mod(boxid + '.dealBoxSubPercent', 1, 20, percent, true, 0, '');
        }
        var discount = Number($(boxid + '.dealBoxDiscount').text().replace('$', ''));
        var price = Number($(boxid + '.dealBoxSubPrice').text().replace('$', ''));
        if (!isNaN(discount)) {
            $(boxid + '.dealBoxDiscount').text($(boxid + '.dealBoxSubPrice').text());
            mod(boxid + '.dealBoxDiscount', -((price - discount) / percent), 20, discount, false, 2, '$');
        }
    });

    //tabs
    $('#r_divFeaturesTabTop').click(function () {
        $('#r_divFeaturesTabTop').removeClass('dealYapFeatureTab1').addClass('dealYapFeatureTabOn1');
        $('#r_divPolicyTabTop').addClass('dealYapFeatureTab2').removeClass('dealYapFeatureTabOn2');
        $('#r_divUsersTabTop').addClass('dealYapFeatureTab3').removeClass('dealYapFeatureTabOn3');
        $('#r_divFeaturesTab').show();
        $('#r_divPolicyTab').hide();
        $('#r_divUsersTab').hide();
        dealTrack('Discount Deals', 'ReviewTabs', 'Features');
    });
    $('#r_divPolicyTabTop').click(function () {
        $('#r_divFeaturesTabTop').addClass('dealYapFeatureTab1').removeClass('dealYapFeatureTabOn1');
        $('#r_divPolicyTabTop').removeClass('dealYapFeatureTab2').addClass('dealYapFeatureTabOn2');
        $('#r_divUsersTabTop').addClass('dealYapFeatureTab3').removeClass('dealYapFeatureTabOn3');
        $('#r_divFeaturesTab').hide();
        $('#r_divPolicyTab').show();
        $('#r_divUsersTab').hide();
        dealTrack('Discount Deals', 'ReviewTabs', 'Policy');
    });
    $('#r_divUsersTabTop').click(function () {
        $('#r_divFeaturesTabTop').addClass('dealYapFeatureTab1').removeClass('dealYapFeatureTabOn1');
        $('#r_divPolicyTabTop').addClass('dealYapFeatureTab2').removeClass('dealYapFeatureTabOn2');
        $('#r_divUsersTabTop').removeClass('dealYapFeatureTab3').addClass('dealYapFeatureTabOn3');
        $('#r_divFeaturesTab').hide();
        $('#r_divPolicyTab').hide();
        $('#r_divUsersTab').show();
        dealTrack('Discount Deals', 'ReviewTabs', 'Users');
    });

    //top toggle
    $('#StoreTop1_lblToggle0').click(function () {
        dealTrack('Discount Deals', 'Nav Toggle', '/');
    });
    $('#StoreTop1_lblToggle1').click(function () {
        dealTrack('Discount Deals', 'Nav Toggle', '/previews');
    });


    //Buy button
    $('body').append('<div id="buypop"></div>');
    $('#buypop').dialog({
        modal: true,
        autoOpen: false,
        height: 300,
        width: 460,
        title: 'Getting Your Bits...',
        zIndex: 3000,
        close: function (ev, ui) {
            try { document.execCommand('Stop'); } catch (ex) { }
            try { window.stop(); } catch (ex) { }
        }
    });
    $('.dealBtnBuy').live('click', function (event) {
        showLoady(event);
        var review = $(this).attr('rel');
        var buytype = $(this).attr('buytype');
        if (buytype == undefined) buytype = '';
        if (buytype == 'Everyday') {
            dealGoal('buyunlimited');
        } else {
            dealGoal('buyit');
        }
        dealTrack('Discount Deal Review', 'Buy' + buytype, review);
        dealTrack('Discount Deal Review', 'Info Buy' + buytype, trackBDJ);
        $('#buypop').load(ajaxpath + 'buy.aspx?review=' + review, [], function () {
            $('#buypop').dialog('open');
            hideLoady();
        });
        return false;
    });
    $('.dealBoxBuyRegular').live('click', function (event) {
        showLoady(event);
        var review = $(this).attr('rel');
        var buytype = $(this).attr('buytype');
        dealGoal('buyregular');
        dealTrack('Discount Deal Review', 'Buy Regular' + buytype, review);
        dealTrack('Discount Deal Review', 'Info Buy Regular' + buytype, trackBDJ);
        $('#buypop').load(ajaxpath + 'buy.aspx?regular=true&review=' + review, [], function () {
            $('#buypop').dialog('open');
            hideLoady();
        });
        return false;
    });
    $('.dealBtnBuyTiny').live('click', function (event) {
        showLoady(event);
        var review = $(this).attr('rel');
        var buytype = $(this).attr('buytype');
        if (buytype == undefined) buytype = '';
        if (buytype == 'Everyday') {
            dealGoal('buyunlimited');
        } else {
            dealGoal('buyit');
        }
        dealTrack('Discount Deal Tiny', 'Buy' + buytype, review);
        dealTrack('Discount Deal Tiny', 'Info Buy' + buytype, trackBDJ);
        $('#buypop').load(ajaxpath + 'buy.aspx?review=' + review, [], function () {
            $('#buypop').dialog('open');
            hideLoady();
        });
        return false;
    });

    //Want button
    $('body').append('<div id="wantload"></div><div id="wantpop"></div>');
    $('#wantpop').dialog({
        modal: true,
        autoOpen: false,
        height: 200,
        width: 480,
        title: 'I Want This',
        zIndex: 2999
    });
    $('.dealBtnIWantThis, .dealBoxButtons .dealWantTick').live('click', function (event) {
        showLoady(event);
        var review = $(this).attr('rel');
        dealGoal('notify');
        dealTrack('Discount Deal Review', 'Want', review);
        dealTrack('Discount Deal Review', 'Info Want', trackBDJ);
        $('#wantload').load(ajaxpath + 'want.aspx?review=' + review);
        return false;
    });
    $('.dealBtnIWantThisTiny, .dealPodButtons .dealWantTick').live('click', function (event) {
        showLoady(event);
        var review = $(this).attr('rel');
        dealGoal('notify');
        dealTrack('Discount Deal Tiny', 'Want', review);
        dealTrack('Discount Deal Tiny', 'Info Want', trackBDJ);
        $('#wantload').load(ajaxpath + 'want.aspx?tiny=true&review=' + review);
        return false;
    });

    //Suggestion Wants
    $('body').append('<div id="wantsuggestload"></div>');
    $('.dealBtnIWantThisSuggest, .dealBoxButtons .dealWantSuggestTick').live('click', function (event) {
        showLoady(event);
        var suggest = $(this).attr('rel');
        dealTrack('Discount Deal Suggestion', 'Want', suggest);
        dealTrack('Discount Deal Suggestion', 'Info Want', trackBDJ);
        $('#wantsuggestload').load(ajaxpath + 'wantsuggest.aspx?isva=' + suggest);
        return false;
    });
    $('.dealBtnIWantThisSuggestTiny, .dealPodButtons .dealWantSuggestTick').live('click', function (event) {
        showLoady(event);
        var suggest = $(this).attr('rel');
        dealTrack('Discount Deal Suggestion', 'Want', suggest);
        dealTrack('Discount Deal Suggestion', 'Info Want', trackBDJ);
        $('#wantsuggestload').load(ajaxpath + 'wantsuggest.aspx?tiny=true&isva=' + suggest);
        return false;
    });

    //login/signup
    if ($('.login, .signup').length > 0) {
        $('body').prepend('<div id="loginpop"></div>');
        $('#loginpop').dialog({
            modal: true,
            autoOpen: false,
            height: 410,
            width: 605,
            title: 'Your Bits',
            zIndex: 3001
        });
        $('.login, .signup').live('click', function (event) {
            showLoady(event);
            dealTrack('Discount Deals', 'Login', $(this).attr('rel'));
            $('#loginpop').load(ajaxpath + 'login.aspx?' + $(this).attr('rel'), [], function () {
                $('#loginpop').dialog('open');
                hideLoady();
            });
            return false;
        });
    }

    //Downloads
    if ($('.dealDownloads').length > 0) {
        $('body').prepend('<div id="downloadspop"></div>');
        $('#downloadspop').dialog({
            modal: true,
            autoOpen: false,
            height: 370,
            width: 260,
            title: 'Choose Your Download',
            zIndex: 2998
        });
        $('.dealDownloads').click(function (event) {
            showLoady(event);
            var review = $(this).attr('rel');
            dealTrack('Discount Deal Review', 'Download', review.replace('review=', ''));
            $('#downloadspop').load(ajaxpath + 'downloads.aspx?' + review, [], function () {
                $('#downloadspop').dialog('open');
                hideLoady();
            });
            return false;
        });
    }

    //Notes
    if ($('.dealNoteMiniOn, .dealNoteOn, .dealNoteMini, .dealNote').length > 0) {
        $('body').prepend('<div id="notespop"></div>');
        $('#notespop').dialog({
            modal: true,
            autoOpen: false,
            height: 320,
            width: 260,
            title: 'Your Private Notes',
            zIndex: 2998
        });
        $('.dealNoteMiniOn, .dealNoteOn, .dealNoteMini, .dealNote').live('click', function (event) {
            showLoady(event);
            var review = $(this).attr('rel');
            dealTrack('Discount Deal Review', 'Notes', review);
            $('#notespop').load(ajaxpath + 'notes.aspx?review=' + review, [], function () {
                $('#notespop').dialog('open');
                hideLoady();
            });
            return false;
        });
    }

    //Comments Rules Popup
    if ($('.commentRules').length > 0) {
        $('body').prepend('<div id="commentrulespop"></div>');
        $('#commentrulespop').dialog({
            modal: true,
            autoOpen: false,
            height: 410,
            width: 410,
            title: 'Rules for Comments',
            zIndex: 3001
        });
        $('.commentRules').live('click', function (event) {
            showLoady(event);
            dealTrack('Discount Deals', 'Comment Rules');
            $('#commentrulespop').load(ajaxpath + 'comment-rules.aspx', [], function () {
                $('#commentrulespop').dialog('open');
                hideLoady();
            });
            return false;
        });
    }

    //DRM Popup
    if ($('.drm').length > 0) {
        $('body').prepend('<div id="drmpop"></div>');
        $('#drmpop').dialog({
            modal: true,
            autoOpen: false,
            height: 410,
            width: 410,
            title: 'License Activation',
            zIndex: 3001
        });
        $('.drm').live('click', function (event) {
            showLoady(event);
            dealTrack('Discount Deals', 'DRM');
            $('#drmpop').load(ajaxpath + 'drm.aspx', [], function () {
                $('#drmpop').dialog('open');
                hideLoady();
            });
            return false;
        });
    }

    //ensure against double clicks on the comments/forum
    $('.dealBtnPost').mouseup(function () {
        setTimeout("if ($('.ErrorMsg:visible').length == 0) { $('.dealBtnPost').attr('href', 'javascript:void(0);').css({ 'cursor': 'default' }); }", 100);
    });

    //Dashboard setup
    $('#dashboard-tabs').tabs({
        ajaxOptions: {
            error: function (xhr, status, index, anchor) {
                $(anchor.hash).html('Waiting for Bits...');
            }
        }, spinner: '',
        select: function (event, ui) {
            $("#dashboard-tabs li a #loady").remove();
            if (ui.index > 0) { $("#dashboard-tabs li a").eq(ui.index).append("<div id='loady'><div></div></div>"); }
            dealTrack('Discount Deals', 'Dashboard Tabs', ui.index);
        },
        load: function (event, ui) {
            hideLoady();
        }
    });

    //set up readmore link
    $('.dealReadMore').live('click', function () {
        var div = $(this).parent();
        var startHeight = div.height();
        div.css('height', 'auto');
        var endHeight = div.height();
        div.height(startHeight).animate({ height: endHeight });
        $(this).hide();
    });

    //set up the multiple post hider
    $('.dealMorePosts').live('click', function () {
        var div = $(this).closest('.dealBubb');
        div.nextAll('.dealBubb').each(function (i, e) {
            if ($(e).find('.dealUserName').text() == div.find('.dealUserName').text()) {
                $(e).slideDown();
            } else {
                return false;
            }
        });
        $(this).slideUp();
        CommExpand();
    });

    CommExpand();

    //old comments list
    if ($('a.dealCommentsOldLink').length > 0) {
        $('a.dealCommentsOldLink').live('click', function (event) {
            showLoady(event);
            var commdata = $(this).attr('rel');
            $('div.commListData[rel="' + commdata + '"]').load(ajaxpath + 'comments.aspx?' + commdata, function () {
                $('.aspNetHidden:not(:first)').remove();    //tide up viewstate
                CommExpand();
                hideLoady();
            });
            $(this).slideUp('slow', function () { $(this).remove(); });
            return false;
        });
    }

    //reply link
    if ($('a.dealReplyLink, a.dealNoReplyLink').length > 0) {
        $('body').append('<div id="replyload"></div><div id="replypop"></div>');
        $('#replypop').dialog({
            modal: true,
            autoOpen: false,
            height: 200,
            width: 480,
            title: 'Manage Email Updates',
            zIndex: 2999
        });
        $('a.dealReplyLink, a.dealNoReplyLink').live('click', function (event) {
            showLoady(event);
            $('#replyload').load(ajaxpath + 'reply.aspx?' + $(this).attr('rel'));
            return false;
        });
    }

    //comments editing
    $('.dealTextEditable').click(function () {
        $(this).parent().hide('slow').parents('.dealBubb').hide('slow').nextAll('.dealTextEdit').css({ 'height': 'auto', 'overflow-y': 'auto', 'overflow-x': 'hidden' }).slideDown('slow');
    });
    $('.dealTextEdit').css({ 'height': 'auto', 'display': 'none' });

    $('.lightbox').click(function () {
        $.fancybox({
            'overlayColor': '#646778',
            'overlayOpacity': 0.3,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 600,
            'speedOut': 200,
            'autoScale': false,
            'padding': 45,
            'href': this.href
        });
        dealTrack('Discount Deal Review', 'Screenshot');
        return false;
    });

    $('.dealVideo').parent().click(function () {
        $.fancybox({
            'overlayColor': '#646778',
            'overlayOpacity': 0.11,
            'padding': 0,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 600,
            'speedOut': 200,
            'title': this.title,
            'width': 680,
            'height': 495,
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
        });
        dealTrack('Discount Deal Review', 'Video');
        return false;
    });

    $('.ancPostWithoutLogin').click(function () {
        $(this).parent().nextAll('table').fadeToggle('slow');
    });

    $('.dealCommentAdminLink').live('click', function () {
        $(this).next('.dealCommentAdminBox').toggle('slow');
    });

    $('.dealNewsletterEmail').live('focus', function () {
        if ($(this).val() == 'enter email') $(this).val('');
    }).live('blur', function () {
        if ($(this).val() == '') $(this).val('enter email');
    });

    $('.dealFloatyClose').click(function () {
        $(this).parent().animate({ height: 0, opacity: 0 }, 300);
        $(this).parent().next().animate({ height: '19px', opacity: 1 }, 300);
        $.cookie('hideFoot', 1, { expires: 180, path: '/' });
        dealTrack('Discount Deals', 'Footer', 'Close');
    });
    $('.dealFloatyOpen').click(function () {
        $(this).animate({ height: 0, opacity: 0 }, 300);
        $(this).prev().animate({ height: '30px', opacity: 1 }, 300);
        $.cookie('hideFoot', 0, { expires: 180, path: '/' });
        dealTrack('Discount Deals', 'Footer', 'Open');
    });

    $('.bdjTopNLClose').click(function () {
        $(this).parent().parent().parent().animate({ height: 0, opacity: 0 }, 300);
        $.cookie('hideBar', 1, { expires: 180, path: '/' });
        dealTrack('Discount Deals', 'SignUpBar', 'Close');
    });

    //Admin Bar
    $('#StoreTop1_chkAdminPromos').click(function () {
        $.cookie('hideAdminPromos', ($(this).is(':checked') ? '0' : '1'), { expires: 180, path: '/' });
        refreshPage();
    });
    $('#StoreTop1_chkAdminLinks').click(function () {
        $.cookie('hideAdminLinks', ($(this).is(':checked') ? '0' : '1'), { expires: 180, path: '/' });
        refreshPage();
    });

    //everyday list
    if ($('a.everyslink').length > 0) {
        $('a.everyslink').live('click', function (event) {
            showLoady(event);
            var pagenumber = $(this).attr('rel');
            $('div.everysdata[rel="' + pagenumber + '"]').load(ajaxpath + 'everydays.aspx?pagenumber=' + pagenumber, function () {
                hideLoady();
            });
            $(this).slideUp('slow', function () { $(this).remove(); });
            return false;
        });
    }

    //activity list
    if ($('a.activitylink').length > 0) {
        $('a.activitylink').live('click', function (event) {
            showLoady(event);
            var pagenumber = $(this).attr('rel');
            $('div.activitydata[rel="' + pagenumber + '"]').load(ajaxpath + 'activity.aspx?pagenumber=' + pagenumber, function () {
                hideLoady();
            });
            $(this).slideUp('slow', function () { $(this).remove(); });
            return false;
        });
    }

    //search form
    $('a#ancSearch').click(function (event) {
        $('span#spnSearchWarning').hide();
        var strS = $('input#txtSearch').val();
        if (strS == '') {
            $('span#spnSearchWarning').show().text('required');
        } else {
            if (strS.length < 3) {
                $('span#spnSearchWarning').show().text('Must be at least 3 characters');
            } else {
                showLoady(event);
                dealTrack('Discount Deals', 'Search', strS);
                $('div.searchdata:first').load(ajaxpath + 'search.aspx?' + '&searchtext=' + encodeURIComponent(strS), function () {
                    hideLoady();
                });
            }
        }
    });

    $('input#txtSearch').keypress(function (e) {
        if (e.keyCode == 13) {
            $('a#ancSearch').click();
            return false;
        }
    });

    //search list
    $('a.searchlink').live('click', function (event) {
        showLoady(event);
        $('div.searchdata[rel="' + $(this).attr('rel') + '"]').load(ajaxpath + 'search.aspx?' + $(this).attr('rel'), function () {
            hideLoady();
        });
        $(this).slideUp('slow', function () { $(this).remove(); });
        return false;
    });

    //suggests list
    $('a.suggestslink').live('click', function (event) {
        showLoady(event);
        $('div.suggestsdata[rel="' + $(this).attr('rel') + '"]').load(ajaxpath + 'suggests.aspx?' + $(this).attr('rel'), function () {
            hideLoady();
        });
        $(this).slideUp('slow', function () { $(this).remove(); });
        return false;
    });

    //Process hash links in url
    if (document.location.hash.indexOf('#want') > -1) {
        $('a.dealBtnIWantThis').click();
    }
    if (document.location.hash.indexOf('#buy') > -1) {
        $('a.dealBtnBuy').click();
    }
    if (document.location.hash.indexOf('#buyregular') > -1) {
        $('a.dealBoxBuyRegular').click();
    }
    if (document.location.hash.indexOf('#download') > -1) {
        if ($('.dealDownloads').length > 0) {
            $('.dealDownloads').click();
        } else {
            document.location.href = $('.dealDownload').attr('href');
        }
    }
    if (document.location.hash.indexOf('#nodownload') > -1) {
        $('body').prepend('<div id="nodownloadspop">This promotion does not have a download available, sorry that you cannot check it out ahead of time but take a careful look at the screenshots and review before making your decision.</div>');
        $('#nodownloadspop').dialog({
            modal: true,
            autoOpen: true,
            height: 200,
            width: 300,
            title: 'No Download Available',
            zIndex: 2998
        });
    }
    if (document.location.hash.indexOf('#stopemails') > -1) {
        $('a.dealReplyLink').click();
    }

    //Twitter
    $('.twitterPopup').live('click', function () {
        window.open('/tweeter', 'twitter', 'width=800,height=450,status=no,location=no,scrollbars=yes');
        return false;
    });

    setupTooltips();


    //grab all the mini reviews from the page
    var pageReviews = [];
    $('.dealPod').each(function (i) {
        $.each($(this).attr('class').split(' '), function (key, val) {
            if (val && val.indexOf('dealPod') == -1 && pageReviews.indexOf(val.replace('r', '')) == -1) {
                pageReviews.push(val.replace('r', ''));
            }
        });
    });
    //get additional data that would have weighed down the page too much
    $.getJSON(ajaxpath + 'pagedata.aspx?reviews=' + pageReviews.join(','), function (data) {
        if (data && data.reviews) {
            $.each(data.reviews, function (key, val) {
                if (val.comments > 0) {
                    $('.r' + key + ' .dealPodComm').hide().text(val.comments).fadeIn('slow');
                }
                if (val.confirmed) {
                    $('<div class="ribPurchasedConfirm"></div>').prependTo('.r' + key).hide().fadeIn('slow');
                } else if (val.purchased) {
                    $('<div class="ribPurchased"></div>').prependTo('.r' + key).hide().fadeIn('slow');
                } else if (val.preowned) {
                    $('<div class="ribPreOwned"></div>').prependTo('.r' + key).hide().fadeIn('slow');
                }
                if (val.notes) {
                    $('.r' + key + ' .dealNoteMini').hide().removeClass('dealNoteMini').addClass('dealNoteMiniOn').fadeIn('slow');
                }
                //console.log('review:' + key + ' :: comments: ' + val.comments + ' purchased:' + val.purchased + ' confirmed:' + val.confirmed + ' preowned:' + val.preowned + ' notes:' + val.notes);
            });
        }
    });

});

//reply link
if ($('a.dealReplyLink, a.dealNoReplyLink').length > 0) {
    $('body').append('<div id="replyload"></div><div id="replypop"></div>');
    $('#replypop').dialog({
        modal: true,
        autoOpen: false,
        height: 200,
        width: 480,
        title: 'Email Updates',
        zIndex: 2999
    });
    $('a.dealReplyLink, a.dealNoReplyLink').live('click', function(event) {
        showLoady(event);
        $('#replyload').load(ajaxpath + 'reply.aspx?' + $(this).attr('rel'));
        return false;
    });
}

//process the reply ajax popup
function doReplyPop(day) {
    day = 'day=' + day;
    if ($('#replyload > a.dealReplyLink[rel="' + day + '"]').length > 0) {
        //process the reply
        $('a.dealReplyLink[rel="' + day + '"]:first').fadeOut('slow', function () {
            $(this).after($('#replyload > a.dealReplyLink[rel="' + day + '"]').parent().html()).fadeIn('slow');
            $(this).remove();
        });

    } else {
        //popup form
        $('#replypop').empty().html($('div.replydata[rel="' + day + '"]')).dialog('open');
        $('div.replydata[rel="' + day + '"] #ancEmail').click(function (event) {
            $('div.replydata[rel="' + day + '"] #spnWarning').hide();

            var emailPattern = /\w+([-+.]\w+)*@\w{1,}([-.]\w+)*\.\w+([-.]\w+)*/;

            var strE = $('div.replydata[rel="' + day + '"] #txtEmail').val();

            if (strE == '' || strE == 'enter email') {
                $('div.replydata[rel="' + day + '"] #spnWarning').show().text('required');
            } else {
                if (!emailPattern.test(strE)) {
                    $('div.replydata[rel="' + day + '"] #spnWarning').show().text('email not valid');
                } else {
                    showLoady(event);
                    $('#replypop').dialog('close');
                    $('#replyload').load(ajaxpath + 'reply.aspx?' + day + '&email=' + encodeURIComponent(strE) + '&stop=' + $('div.replydata[rel="' + day + '"] #chkStop:checked').val());  //reload the popup with the email address
                }
            }
        });

    }
    hideLoady();
}


//process the notes ajax popup
function doNotesPop(review) {
    $('#notespop #ancOK').click(function (event) {
        //popup form
        showLoady(event);
        $('#notespop').load(ajaxpath + 'notes.aspx', { postback: true, text: $('#txtNote').val(), review: review, confirm: $('#chkConfirm:checked').val(), 'delete': $('#chkDelete:checked').val(), own: $('#chkOwn:checked').val() });  //reload the popup with the data
        $('#notespop').dialog('close');
        hideLoady();
        refreshPage();
    });
}



//process the want ajax popup
function doWantPop(review, tiny, add) {

    if ($('#wantload > div.dealBoxButtons[rel="' + review + '"]').length > 0) {
        //process the want
        if (add) {
            $('a.dealBtnIWantThis[rel="' + review + '"]').parent().fadeOut('slow', function() {
                $(this).before('<div class="dealBoxButtons">' + $('#wantload > div.dealBoxButtons[rel="' + review + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        } else {
            $('div.dealWantIcons[rel="' + review + '"]').parent().fadeOut('slow', function() {
                $(this).before('<div class="dealBoxButtons">' + $('#wantload > div.dealBoxButtons[rel="' + review + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        }

    } else if ($('#wantload > div.dealPodButtons[rel="' + review + '"]').length > 0) {
        //process the want - tiny
        if (add) {
            $('a.dealBtnIWantThisTiny[rel="' + review + '"]').parent().fadeOut('slow', function() {
                $(this).before('<div class="dealPodButtons">' + $('#wantload > div.dealPodButtons[rel="' + review + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        } else {
            $('div.dealWantTick[rel="' + review + '"]').parents('div.dealPodButtons').fadeOut('slow', function() {
                $(this).before('<div class="dealPodButtons">' + $('#wantload > div.dealPodButtons[rel="' + review + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        }
        
    } else {
        //popup form
        $('#wantpop').empty().html($('div.wantdata[rel="' + review + '"]')).dialog('open');
        $('div.wantdata[rel="' + review + '"] #ancEmail').click(function(event) {
            $('div.wantdata[rel="' + review + '"] #spnWarning').hide();

            var emailPattern = /\w+([-+.]\w+)*@\w{1,}([-.]\w+)*\.\w+([-.]\w+)*/;

            var strE = $('div.wantdata[rel="' + review + '"] #txtEmail').val();

            //Get checkbox value for daily bits signup:
            var daily = $('div.wantdata[rel="' + review + '"] #chkDailyBits:checked').length > 0 ? '1' : '0';

            if (strE == '' || strE == 'enter email') {
                $('div.wantdata[rel="' + review + '"] #spnWarning').show().text('required');
            } else {
                if (!emailPattern.test(strE)) {
                    $('div.wantdata[rel="' + review + '"] #spnWarning').show().text('email not valid');
                } else {
                    showLoady(event);
                    $('#wantpop').dialog('close');
                    $('#wantload').load(ajaxpath + 'want.aspx?review=' + review + (tiny ? '&tiny=true' : '') + '&email=' + encodeURIComponent(strE) + '&daily=' + daily);  //reload the popup with the email address
                }
            }
        });

    }
    hideLoady();
}

//process the suggest want ajax popup
function doWantSuggestPop(suggest, tiny, add) {

    if ($('#wantsuggestload > div.dealBoxButtons[rel="' + suggest + '"]').length > 0) {
        //process the want
        if (add) {
            $('a.dealBtnIWantThisSuggest[rel="' + suggest + '"]').parent().fadeOut('slow', function() {
                $(this).before('<div class="dealBoxButtons">' + $('#wantsuggestload > div.dealBoxButtons[rel="' + suggest + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        } else {
            $('div.dealWantIcons[rel="' + suggest + '"]').parent().fadeOut('slow', function() {
                $(this).before('<div class="dealBoxButtons">' + $('#wantsuggestload > div.dealBoxButtons[rel="' + suggest + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        }

    } else if ($('#wantsuggestload > div.dealPodButtons[rel="' + suggest + '"]').length > 0) {
        //process the want - tiny
        if (add) {
            $('a.dealBtnIWantThisSuggestTiny[rel="' + suggest + '"]').parent().fadeOut('slow', function() {
                $(this).before('<div class="dealPodButtons">' + $('#wantsuggestload > div.dealPodButtons[rel="' + suggest + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        } else {
            $('div.dealWantSuggestTick[rel="' + suggest + '"]').parents('div.dealPodButtons').fadeOut('slow', function() {
                $(this).before('<div class="dealPodButtons">' + $('#wantsuggestload > div.dealPodButtons[rel="' + suggest + '"]').html() + '</div>').fadeIn('slow');
                $(this).remove();
            });
        }

    }
    hideLoady();
}

function setupTooltips() {
    //snazzy tooltips
    $('.dealPod a[title], .dealFloaty[title], .tooltrigger').tooltip({ effect: 'slide', predelay: 500 });
}

function hideTooltips() {
    $('.tooltip').fadeOut('slow');
}

//to show loading icon
function showLoady(event) {
    hideTooltips(); 
    if ($('#loady').length == 0) {
        $('body').append('<div id="loady"><div></div></div>');
    }
    $('#loady').css({ 'display':'block', 'top':(event.pageY-13), 'left':(event.pageX-13) });
}

//to hide loading icon
function hideLoady() {
    setupTooltips();
    $('#loady').hide();
}


function CommExpand() {
    //set up comments expander
    $('.dealText').each(function(i, e) {
        if ($(e).height() > 147 && $(e).parent().has('.dealReadMore').length == 0) {
            $(e).css({ height: '148px', maxHeight: 'none' });
            $(e).prepend('<a class="dealReadMore">more</a>');
            $(e).children('.dealReadMore').width($(e).width());
        }
    });
    //set up the multiple post hider
    var lastItem;
    $('.dealBubb').each(function (i, e) {
        if ($(e).is(':visible')) {
            lastItem = $(e);
        } else {
            if (lastItem && $(e).find('.dealUserName').text() == lastItem.find('.dealUserName').text()) {
                if (lastItem.find('.dealMorePosts').length == 0) {
                    var posts = 0;
                    lastItem.nextAll('.dealBubb').each(function (ii, ee) {
                        if ($(ee).find('.dealUserName').text() == lastItem.find('.dealUserName').text()) {
                            posts++;
                        } else {
                            return false;
                        }
                    });

                    lastItem.find('.dealBubbMid').append('<a class="dealMorePosts">Read ' + posts + ' More Post' + (posts > 1 ? 's' : '') + ' By ' + lastItem.find('.dealUserName').text() + '</a>');
                }
            }
        }
    });
}

//Google Analytics action tracking
function dealTrack(category, action, label, value) {
    try {
        _gaq.push(['_trackEvent', category, action, label, value]);
    } catch (e) { }
}
function dealGoal(page) {
    try {
        _gaq.push(['_trackPageview', page]);
    } catch (e) { }
}

function Expandax(link) {
	$(link).fadeOut('slow').next().fadeIn('slow');
}


function RevealOldComments(cid) {
    $('#ancOldComments_' + cid).hide();
    $('#ancOldCommentsHide_' + cid).css({ display: 'inline' }).show();
    $('#divOldComments_' + cid).slideDown('slow');
    CommExpand();
}
function HideOldComments(cid) {
    $('#ancOldComments_' + cid).css({ display: 'inline' }).show();
    $('#ancOldCommentsHide_' + cid).hide();
    $('#divOldComments_' + cid).slideUp('slow');
}

function dealBtnOver(objAnc) {
	window.status = objAnc.title;
}

function dealBtnOut() {
	window.status = '';
}

function popupFriend(url) {
	window.open(url, 'help', 'width=450,height=620,status=no,location=no,scrollbars=yes');
}

function popupHelp(url) {
	window.open(url, 'help', 'width=400,height=350,status=no,location=no,scrollbars=yes');
}

function doPercentage(objRegularPrice, objDiscountPrice, objPercentageSaving) {
	var objReg = document.getElementById(objRegularPrice);
	var objDis = document.getElementById(objDiscountPrice);
	var objSpn = document.getElementById(objPercentageSaving);
	var intPercent = 0;
	if (objReg && objDis && objSpn) {
		if ((objReg.value.length > 0) && (objDis.value.length > 0)) {
			intPercent = Math.ceil(100 - objDis.value / objReg.value * 100);
		}
		switch (true) {
			case (intPercent < 30):
				objSpn.innerHTML = intPercent + '% <small style="font-weight:bold;color:#E60000">Too Low</small>';
				break;
			case ((intPercent >= 30) && (intPercent < 40)):
				objSpn.innerHTML = intPercent + '% <small style="font-weight:bold;color:#F39302">Poor</small>';
				break;
			case ((intPercent >= 40) && (intPercent < 45)):
				objSpn.innerHTML = intPercent + '% <small style="font-weight:bold;color:#02C519">OK</small>';
				break;
			case ((intPercent >= 45) && (intPercent < 50)):
				objSpn.innerHTML = intPercent + '% <small style="font-weight:bold;color:#02C519">Good</small>';
				break;
			case ((intPercent >= 50) && (intPercent < 60)):
				objSpn.innerHTML = intPercent + '% <small style="font-weight:bold;color:#02C519">Very Good</small>';
				break;
			case ((intPercent >= 60)):
				objSpn.innerHTML = intPercent + '% <small style="font-weight:bold;color:#02C519">Excellent!</small>';
				break;
		}
	}
}

function refreshPage() {
    if (reloadURL) {
        document.location.href = reloadURL;
    } else if (document.location.href.indexOf('#') < 0) {
        document.location.href = document.location.href;
    } else {
        document.location.href = document.location.href.substring(0, document.location.href.indexOf('#'));
    }
}

function twitterConnected() {
    window.opener.twitterConnectedDone();
    window.close();
}

function twitterConnectedDone() {
    //review
    $('.twitterCheckbox').removeClass('twitterPopup');
    $('.twitterCheckbox input').attr('checked', true);
    //profile
    $('.twitterButton').val('Remove Twitter Connection').removeClass('twitterPopup');
    $('#divTwitShareBuy').show();
    $('#divTwitShareWant').show();
}
