var currentTab, previousTab, tabCount;
previousTab = null;
var animstarted = false;
var imgdir = '/images/dishmicro1/';
var offerboxcolor = ['obgreen', 'obred', 'obblue', 'obgrey'];
var animbg = ['bgtab_lobby.jpg', 'bgtab_office.jpg', 'bgtab_bar.jpg', 'bgtab_hotel.jpg'];

$(document).ready(function () {

    //set first animation tab active
    //$('#slidenav ul li:first').addClass('sel');

    //preload bg images
    bgpreload();

    //subpage header drop animation
    reset($('.subimg h2'));
    $('.subimg h2').gx({ 'top': "+=50px" }, 500, "Linear");

    //homepage animation
    $('.anim').hide();
    $('.anim').eq(0).show();

    tabCount = $('#slidenav ul li a').length
    $('#slidenav ul li a').click(function () {
        $('#slidenav ul li.sel').removeClass('sel');
        $(this).parent().addClass('sel');
        clearAnimation();
        $(this).blur();
        if (!animstarted) {
            animstarted = true;
            doAnimation();
        }
        return false;
    });

    /*
    $('#slidenav ul li a').one("click", function () {
    doAnimation();
    });
    */

    $('.anim .menu ul li a').click(function () {
        $(this).blur();
        //return false;
    });

    //do animation once onload
    //doAnimation();

    //ie7 fix for tab widths
    $('#slidenav .bot').each(function () {
        $(this).css({ 'width': '0px' });
        $(this).css({ 'width': $(this).parent().width() + 'px' });
    });

    //fix currency formatting
    fixCurrency();

    //colorize homepage offer boxes
    $('.offerbox').each(function (index) {
        $(this).addClass(offerboxcolor[index % 4]);
    });

    //colorize subpage offer boxes
    $('.smofferbox').each(function (index) {
        $(this).addClass('sm' + offerboxcolor[index % 4]);
    });

    //resize offer boxes
    equalHeight($('.smofferbox .content'), 30);
    equalHeight($('.offerbox .content, #allpkgs_xtra .mid'), 40);

    //Launch SaleForce Form on "Get Started" clicks
    $("#popper").dialog({
        autoOpen: false,
        width: 750,
        height: 520,
        zIndex: 999999,
        modal: true,
        autoResize: true,
        title: 'Get Started with DISH!'
    });

    $("#popper").html('<iframe src="/dish_sf.aspx" width="710" height="450px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>');


    //GetStarted triggers
    $('a.getstarted, .getstarted a, .panelstart').click(function () {
        openGetStarted();
        //$("#popper").html('<iframe src="/dish_sf.aspx" width="710" height="450px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>');
        //$("#popper").dialog('open');
        return false;
    });

    $('#goPBuilder').click(function () {
        closeGetStarted();
        window.location.href = '/packagebuilder';
        return false;
    });

    $('#goSFForm').click(function () {
        closeGetStarted();
        popSFForm('std');
        return false;
    });

    $('#pol_close').click(function () {
        closeGetStarted();
    });

    //Remove "Get Started" button if on Package Builder
    $('#pkgcart').length ? $('#TitleContainer').hide() : $.noop();

    //fix bottom border on animation menu items
    $('.menu .mid ul').each(function () {
        //log($(this).find('li:last'));
        $(this).find('li:last').css({ 'border-bottom': '1px solid #AAAAAA' });
    });

    //Never highlight "Type of Businness menu item
    $('#nav ul li').eq(2).removeClass('sel');

    //Remove "Learn More", change "Recommended Packages:" to "Features:" on Aprtments/Hotels page 
    if (window.location.pathname == '/hotels') {
        $('#sub_pkgs h2.white').html('Features:');
        $('.smofferbox a').each(function () {
            if ($(this).attr('class') != 'getstarted') {
                $(this).hide();
            }
        });
    }

});


/*******************
* Popup SalesForce form
*******************/
function popSFForm(source, pkgs) {
    var src = '';
    src = source == 'pb' ? '?src=Package%20Builder&pkgs=' + pkgs : '?src=Micro%20Site&pkgs=' + pkgs;
    $("#popper").html('<iframe src="/dish_sf.aspx' + src + '" width="710" height="450px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>');
    $("#popper").dialog('open');
}

/*******************
* Show overlay
*******************/
function openGetStarted() {

    var doc = $(document),
            docwidth = doc.width(),
            docheight = doc.height(),
            overlay = $('<div id="de_overlay"></div>').appendTo('body'),
            popup = $('#getstartedPop'),
            _left = 0,
            _top = 0;

    _left = (docwidth / 2) - (popup.width() / 2);
    _top = ($(window).height() / 2) - (popup.height() / 2);

    overlay.css({ 'width': docwidth + 'px', 'height': docheight + 'px' });
    popup.css({ 'display': 'block', 'left': _left + 'px', 'top': _top + 'px', 'position': 'fixed' });

}

/*******************
* Hide overlay
*******************/
function closeGetStarted() {
    var popup = $('#getstartedPop');

    $('#de_overlay').remove();
    popup.css({ 'display': 'none' });
}

//This function extends the math class to create a guid for using to ensure no caching
(function () {
    // Private array of chars to use
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    Math.uuidFast = function () {
        var chars = CHARS, uuid = new Array(36), rnd = 0, r;
        for (var i = 0; i < 36; i++) {
            if (i == 8 || i == 13 || i == 18 || i == 23) {
                uuid[i] = '-';
            } else if (i == 14) {
                uuid[i] = '4';
            } else {
                if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                r = rnd & 0xf;
                rnd = rnd >> 4;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
        return uuid.join('');
    };
})();


//preload bg images
function bgpreload() {
    var imgs = new Array();
    for (i = 0; i < animbg.length; i++) {
        imgs[i] = new Image();
        imgs[i].src = imgdir + animbg[i];
    }
}

function doAnimation() {
    //get currentlt selected tab
    currentTab = $('#slidenav ul li.sel').index();
    if (isNaN(currentTab)) {
        currentTab = 0;
    }
    //reset all positions/states
    reset($('.flyoutcontent div'));
    reset($('.menu'));
    reset($('.flyout'));
    reset($('.pointer'));
    reset($('.bgimg h2'));
    //hide outermost stuff
    $('.anim').hide();
    $('.flyoutcontent > div').hide();
    //show the animation related to the current tab
    $('.anim:eq(' + currentTab + ')').show();
    $('.anim:eq(' + currentTab + ') .flyoutcontent div:first').show();
    //set bg image
    $('.anim:eq(' + currentTab + ') .bgimg').css({ 'background-image': 'url(' + imgdir + animbg[currentTab] + ')' });
    //slide stuff in, or out
    $('.anim:eq(' + currentTab + ') .menu').gxInit({ queue: 'cancel' });
    $('.anim:eq(' + currentTab + ') .menu').gxInit({ delay: 100 });
    //drop current menu in
    $('.anim:eq(' + currentTab + ') .menu').gx({ 'top': '+=0' }).gx({ 'top': '+=440' }, 1050, 'Cubic:InOut', {
        start: function () { ; },
        complete: function () {
            //check for opacity support (pfft, IE)
            if (jQuery.support.opacity) {
                $('.anim:eq(' + currentTab + ') .flyout').fadeIn('slow');
                $('.anim:eq(' + currentTab + ') .pointer').fadeIn('slow');
            } else {
                $('.anim:eq(' + currentTab + ') .flyout').show();
                $('.anim:eq(' + currentTab + ') .pointer').show();
            }

            //adjust flyout position
            var flyout = $('.anim:eq(' + currentTab + ') .flyoutcontent > div').eq(0);
            adjustFlyout(flyout);

        }
    });
    $('.anim:eq(' + currentTab + ') .bgimg h2').gx({ 'top': "+=50px" }, 500, "Linear");
    //follow the mouse and change content
    $('.anim:eq(' + currentTab + ') .menu ul li a').mouseenter(function () {
        currentIndex = $(this).parent().prevAll().length;   //determine current index

        $('.anim:eq(' + currentTab + ') .pointer').gxInit({ queue: 'cancel' });
        $('.anim:eq(' + currentTab + ') .pointer').gx({ 'top': $(this).offset().top - $('.anim:eq(' + currentTab + ')').offset().top + 'px' }, 1, 'Linear', {
            start: function () { ; },
            complete: function () {
                $('.anim:eq(' + currentTab + ') .flyoutcontent > div').hide();
                $('.anim:eq(' + currentTab + ') .flyoutcontent > div').eq(currentIndex).show();

                //adjust flyout position
                var flyout = $('.anim:eq(' + currentTab + ') .flyoutcontent > div').eq(currentIndex);
                adjustFlyout(flyout);
                //var topto = ((flyout.parent().parent().parent().parent().height() - (flyout.height() + 23 + 23 + 32)) / 2) + 20;
                //flyout.parent().parent().css({ 'top': topto + 'px' });

            }
        });
    });
    previousTab = currentTab;
}

function clearAnimation() {
    if (previousTab != null) {
        $('.anim:eq(' + previousTab + ') .menu').gxInit({ delay: 100 });
        $('.anim:eq(' + previousTab + ') .menu').gx({ 'top': '+=440' }, 1000, 'Cubic:InOut', {
            start: function () { ; },
            complete: function () { doAnimation(); }
        });
        //drop previous menu out
        //check for opacity support (pfft, IE)
        if (jQuery.support.opacity) {
            $('.anim:eq(' + previousTab + ') .flyout').fadeOut('slow');
            $('.anim:eq(' + previousTab + ') .pointer').fadeOut('slow');
        } else {
            $('.anim:eq(' + previousTab + ') .flyout').hide();
            $('.anim:eq(' + previousTab + ') .pointer').hide();
        }
        $('.anim:eq(' + previousTab + ') .bgimg h2').gx({ 'top': "-50px" }, 500);
    }
}

//remove inline styles for given element
function reset(el) {
    el.attr('style', ''); //webkit fix
    el.removeAttr('style');
}

function adjustFlyout(flyout) {
    /*var topto = ((flyout.parent().parent().parent().parent().height() - (flyout.height() + 23 + 23 + 32)) / 2) + 20;
    flyout.parent().parent().css({ 'top': topto + 'px' });*/
}

function warble(color, duration) {
    //call warble('#00ff00', 30000);
    $('body').gx({ 'background-color': color }, duration, 'Linear', {
        start: function () { ; },
        complete: function () { log('DONE.'); $('body').css('background-color') == 'rgb(0, 255, 0)' ? warble('#ffffff', duration) : warble('#00ff00', duration); }
    });
}

function fixCurrency() {
    //var re = /(\$)(\d+\.)(\d+)/;
    var re = /(\$)(\d+)(\/mo)/;
    var raw = "";
    var mod = "";

    $('.currency').each(function () {
        raw = $(this).html();
        if ($('.flyoutcontent').length > 0) {
            mod = raw.replace(re, '<div class="currencyjq"><div class="dollarsign">$1</div><div class="dollaramt">$2</div><div class="centamt">$3*</div><div class="clr"></div></div>');
        } else {
            mod = raw.replace(re, '<div class="currencyjq"><div class="startingat">starting at </div><div class="dollarsign">$1</div><div class="dollaramt">$2</div><div class="centamt">$3</div><div class="clr"></div></div>');
        }
        
        $(this).after(mod).remove();
    });
}

function equalHeight(group, addheight) {
    var tallest = 0;

    if (addheight == undefined) {
        addheight = 0;
    }

    group.each(function () {
        var thisHeight = $(this).height() + addheight;
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

function closeOverlay() {
    $('.ui-dialog-titlebar-close').click();
}

function log(msg) {
    if ("undefined" != typeof (console)) {
        console.log(msg);
    }
}

//basic AJAX caller; returns the response; function accepting must interpret correctly
function execAJAX(sClass, sAction, sParams, sDataType, sType, bAsync) {
    var retval = null;
    var json = "{";
    json = json + formatJSONNameValue("t", sClass, false);
    json = json + formatJSONNameValue("a", sAction, true);
    json = json + formatJSONNameValue("p", sParams, true);
    json = json + formatJSONNameValue("g", Math.uuidFast(), true);
    json = json + "}";
    var data = $.ajax({
        url: "/ajax/__ajax.aspx",
        async: bAsync,
        dataType: sDataType,
        type: sType,
        data: { "t": "" + sClass + "", "a": "" + sAction + "", "p": "" + sParams + "", "g": "" + Math.uuidFast() + "" },
        success: function (response) {
            retval = response;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('AJAX ERROR: ' + xhr.status + ' - ' + thrownError);
        }
    });
    return retval;
}

//formats a name value pair for a json string
function formatJSONNameValue(name, value, prependComma) {
    var retval = "";
    if (prependComma) { retval = "," }
    retval = retval + name + ":\"" + value + "\""
    return retval
}

