
//TMobile Navigation Plugin
//
// Create closure
//
(function($) {
    var tmNavData = null;
    var subnavT, dropdownT, activeNav, activeSubNav, tmopath;

    //
    // Plugin definition
    //
    $.fn.TMobileNavigation = function(options) {


        // build main options before element iteration
        var opts = $.extend({}, $.fn.TMobileNavigation.defaults, options);

        // iterate and reformat each matched element
        return this.each(function() {

            $this = $(this);
            // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            var thisId = $this.attr('id');
            var appId = $this.attr('appId');
            var supportspanish = $this.attr('supportspanish');
            var section = $this.attr('section');
            var isHomePage = section == null ? false : section == "Homepage" ? true : false;
            //alert(isHomePage);
            tmopath = $this.attr('tmopath');
            var spanishUrl = $this.attr('SpanishUrl');
            var fetchJSUNav = ($('#head').html()==null || $.trim($('#head')[0].innerHTML).length==0)? true : false;

            if (appId == null && thisId == 'foot') {
                appId = $('#head').attr('appId');
                tmopath = $('#head').attr('tmopath');
            }
            else if (appId == null)
                appId = "tmobile";

            if (thisId == 'head') {
              if (fetchJSUNav) {
                $.getJSON(tmopath + "/htmlservices/navigation/TMobileNavigation.ashx?func=tmo&appId=" + appId + "&supportspanish=" + supportspanish + "&section=" + section + "&format=json&jsoncallback=?", function(navigationData) {
                    tmNavData = navigationData;

                    tmAddHeaderHTML();
                    tmNavSetFooter();
                    initSearch();
                    initNav();
                    tm_spanish_Check(tmNavData.SpanishUrl);
                });
            }
            else {
                tm_spanish_Check(spanishUrl);
                initNav();
                initSearch();
            }
                               
               
            }
        });
    };

    // Keeps the footer properly lined up
    (function() {
        this.fixFooter = function() {
            try {
                var footElem = document.getElementById('bottom') ?
					document.getElementById('bottom') : document.getElementById('foot');

                var pageElem = document.getElementById('bottom') ?
					document.getElementById('wrapper') : document.getElementById('page');

                if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
                    // IE
                    var c = getClientHeight();
                    var f = footElem.offsetHeight;
                    if (c > f) {
                        pageElem.style.height = parseInt(c - f - 100) + 'px';
                    }
                }
                else if (!($.browser.msie)) {
                    pageElem.style.minHeight = parseInt(getClientHeight() - footElem.offsetHeight) + 'px';
                }
            }
            catch (ex) { }
        }
    }
    )();

    (function() {
        this.tmAddHeaderHTML = function() {
            $('#head').html(tmNavData.HeaderHTML);
        };
    })();
    
    
    (function() {
        this.checkSearchEnter = function(e) {

            try {
                var characterCode;
                if (e && e.which) {
                    e = e;
                    characterCode = e.which;
                }
                else {
                    e = event;
                    characterCode = e.keyCode;
                }

                if (characterCode == 13) {
                    doSearch();
                    return false;
                }
                else {
                    return true;
                }
            } catch (e) { return true; }
        };
    })();

    (function() {
        this.doSearch = function() {

            var question = document.getElementById('SearchForaQuestion').value;

            if (!(question.length) || question == 'Buscar en T-Mobile') {
                $('SearchForaQuestion').focus();
                return false;
            } else if (question.length > 200) {
                alert('Tu pregunta es demasiado larga. Puede ser reducida a 200 caracteres.');
            }
            var val = question.replace(/</g, "").replace(/>/g, "").replace(/\(/g, "").replace(/\)/g, "").replace(/&/g, "");
            window.location.href = tmopath + "/Search/?ui_mode=question&question_box=" + val;
            return false;
        };
    })();

    (function() {
        this.popLink = function(url, width, height) {
            window.open(url, 'popped', 'width=' + width + ',height=' + height + ',screenX=568,screenY=400,left=50,top=50,toolbar=no,location=no,menubar=no,status=no,resizable,scrollbars');
            return false;
        }
    })();

    (function() {
        this.tmNavSetFooter = function() {

            $('#foot').html(tmNavData.FooterHTML);
        };
    })();

    function hideSubNav(obj) {

        obj = (obj == null || obj == 'undefined') ? $('.topnav .secondlvl') : $(obj);
        subnavT = setTimeout(function() {

            $(obj).hide();
            showSubNav(activeSubNav);
            $('.topnav > li').removeClass('selected');
            activeNav.addClass('selected');
        }, 500);
    }
    function showSubNav(obj) {
        clearTO(subnavT);
        if (obj) $(obj).show();
    }
    function clearTO(t) {
        if (t) {
            clearTimeout(t);
            t = null;
        }
    }


    function initNav() {
        /* init page components */
        $('.smartval').smartval();

        /* Init Site Navigation
        ############################################## 
        */

        $('.dropdown').hover(
        function() {
            $('.topnav > li').find('li.dropdown').removeClass('subnavactive');  // hides the dropdown if opened from a tab focus on a mouseover
            $('.topnav .secondlvl').find('li .thirdlvl li a').blur();  // removes the tab focus from an element on a mouseover
            $(this).addClass('subnavactive').setNav3Width(); ;
        },  // over
        function() {
            $(this).removeClass('subnavactive');
        }   // out
    );






        $('.topnav > li > .secondlvl').show().hide();  /* resets nav */
        // get defaults
        activeNav = $('.topnav > .selected');
        activeSubNav = $(activeNav).find('.secondlvl').show();

        // hover
        $('.topnav > li > a').hover(
				function() {                      // over
				    $('.topnav .secondlvl').hide();
				    showSubNav($(this).next());
				},
				function() { hideSubNav(); }      // out
  );
        $('.secondlvl').hover(
				function() { clearTO(subnavT); }, // over
				function() { hideSubNav(); } 		  // out
  );

        // keyboard access
        $('.topnav > li > a').focus(function() {
            clearTO(subnavT);
            $('.topnav > li').removeClass('selected');
            $(this).parent().addClass('selected');
            $('.topnav .secondlvl').hide();
            showSubNav($(this).next());

            // clears the dropdown style if shift-tabbing through the list
            $(this).parent().find('li:first-child').removeClass('subnavactive')

        });
        $('.topnav > li > a').blur(function() {
            hideSubNav();
        });
        $('.topnav .secondlvl > li > a').focus(function() {
            clearTO(subnavT);

            // clears the dropdown style if shift-tabbing through the list       
            $(this).parents('li').next().removeClass('subnavactive');

            if ($(this).parent('li').hasClass('dropdown')) {
                $(this).parent().addClass('subnavactive').setNav3Width();
            }

        });
        $('.topnav .secondlvl > li > a').blur(function() {
            hideSubNav();
        });

        $('.topnav .secondlvl > li.dropdown li:last-child a').blur(function() {
            $(this).parents('li.dropdown').removeClass('subnavactive');
        });

        // for shift-tabbing through a third-level dropdown list
        $('.topnav .secondlvl > li.dropdown li a').focus(function() {
            if (!$(this).parent('li').hasClass('subnavactive')) {
                $(this).parents('li.dropdown').addClass('subnavactive');
            }
        });


        // click enable
        $('.topnav > li > a').click(function(event) {
            $('.topnav > li').removeClass('selected');
            $(this).parent().addClass('selected');

            activeNav = $('.topnav > .selected');
            activeSubNav = $(activeNav).find('.secondlvl');
        });

        $('#password-clear').show();
        $('#myTMobile-password').hide();

        $('#password-clear').focus(function() {
            $('#password-clear').hide();
            $('#myTMobile-password').show();
            $('#myTMobile-password').focus();
        });
        $('#myTMobile-password').blur(function() {
            if ($('#myTMobile-password').val() == '') {
                $('#password-clear').show();
                $('#myTMobile-password').hide();
            }
        });

    }

    function poptastic(url, height, width, top, left, toolbar, resize, scrollbars) {
        var pop = window.open(url, 'popup', 'height=' + height + ',width=' + width + ',top=' + top + ',left=' + left + ',toolbar=' + toolbar + ',resizable=' + resize + ',scrollbars=' + scrollbars);
        if (typeof window.focus != 'undefined') javascript: pop.focus();
    }
    //
    // End of closure
    //
})(jQuery);

/* <!-- mp_trans_disable_start --> */
function tm_spanish_setCookie(B, A) {
    document.cookie = B + '=' + A + ';path=/;domain=t-mobile.com;';
}

function tm_spanish_Check(spanishUrl) {
    
    if (window.location.href.toLowerCase().indexOf(spanishUrl) != -1) {
        tm_spanish_setCookie('TMobileSpanish', 'IsSpanishUser=true');
        document.getElementById('Spanish').innerHTML = 'Español';
    }
    else {
        tm_spanish_setCookie('TMobileSpanish', 'IsSpanishUser=false');
        document.getElementById('English').innerHTML = 'English';
    }
}
/* <!-- mp_trans_disable_end --> */


$(document).ready(function() {
$('#head').TMobileNavigation();

window.onresize = fixFooter;
fixFooter();

});

$(document).ajaxError(function(event, request, settings) {
    //alert(request);
    //alert(event);
    //alert(settings);
});
$(document).ajaxStop(function() {
    //alert(this);
});

jQuery.fn.setNav3Width = function() {
    var currentWidest = this.find('a:first-child').width() + 20;
    this.find('ul.thirdlvl, ul.thirdlvl li').css({ 'width': 'auto', 'min-width': '0px' });
    this.find('ul.thirdlvl li').each(function() {
        if (jQuery(this).width() > currentWidest) { currentWidest = jQuery(this).width(); }
    }).css('width', currentWidest + "px");
    return this;
}