function GetMap(map_width, map_height, zipcode) {

    map_width = typeof (map_width) != 'undefined' ? map_width : $('#map').width();
    map_height = typeof (map_height) != 'undefined' ? map_height : $('#map').height();
    zipcode = typeof (zipcode) != 'undefined' ? zipcode : currentOffice;

    map = new VEMap('map');
    map.SetCredentials(bingAPIKey);
    map.LoadMap();
    map.Resize(map_width, map_height);
    //map.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
    //map.Find("Jackson Hewitt", zipcode, VEFindType.Businesses, null, 0, 20, true, null, true, true, listLocations);
    map.Find(null, zipcode, VEFindType.Business, null, 0, 10, true, false, true, true, null);
    listLocations();
    AddPins(map);

}

function listLocations() {

    totalStores = $("#listings_table tr").length;
    $("#totalstores").text(totalStores);
    maxpages = Math.ceil(totalStores / 20);
    setPage();

    $("#listings_table tr:nth-child(even)").addClass("leven");

    $("#listings_table").jScrollPane({
        scrollbarWidth: 17,
        scrollbarMargin: 0,
        showArrows: true
    });

    PrepShadowboxes();



}

function setPage() {
    $("#listings_table tr").each(function() {
        var idx = $("#listings_table tr").index(this) + 1;
        if (idx < ((currpage - 1) * 20) || idx > (currpage * 20)) {
            $(this).hide();
        }
        else {
            $(this).show();
        }
    });
    //set the current stores 
    var startnum = ((currpage - 1) * 20) + 1;
    var endnum = Math.min((currpage * 20), totalStores);

    $("#currentstores").text(startnum + "-" + endnum);
}
function newZipSearch() {
    GetMap(null, null, $('#zip').val());
    return false;
}

function PrepList() {

    $('ul.exp_points').addClass("clearfix");

    $('ul.exp_points li ul li:first-child').addClass("title");
    $('ul.exp_points li ul li:last-child').hide().css({ 'width': '95%', 'position': 'relative' });

    $('ul.exp_points li ol li:first-child').removeClass("title");
    $('ul.exp_points li ol li:last-child').show().css({ 'width': '', 'position': '' });

    $('ul.exp_points li ul li:first-child').toggle(function() {
        $(this).addClass("selected");
    }, function() {
        $(this).removeClass("selected");
    });
    $('ul.exp_points li ul li:first-child').click(function() {
        $(this).next("li").slideToggle("slow");
    });

}
function fixlists(selector, rewrapped) {

    if (rewrapped == true) {
        $(selector + ' > div > div.inner, ' + selector + ' > div > ul').clone().appendTo('#products');
        $(selector).remove();
    }

    target = $(selector);
    pointer = target.next();

    target.children().each(function(i) { $(this).replaceWith("<p>" + $(this).text() + "<\/p>"); });

    pointer.attr('style', 'margin-bottom:20px');
    pointer.attr('class', 'exp_points');
    pointer.children('li:empty').remove();
    pointer.children('ul').wrap('<li />');

}

function PrepShadowboxes() {

    Shadowbox.init({
        skipSetup: true,
        players: ["iframe"],
        viewportPadding: 40
    });

    $('.office_options a.sb').each(function() {
        Shadowbox.setup($(this), {
            content: $(this).attr("href"),
            player: "iframe",
            width: "1024",
            height: "640",
            title: $(this).text()
        });
    });

}

function AddPins(map) {
    //get all of the office locations
    var counter = 1;
    $(".vcard").each(function() {

        if (totalStores <= 40 || $(this).is(":visible")) {


            var address = $(".street-address", this).text();
            var city = $(".locality", this).text();
            var state = $(".region", this).text();
            var zip = $(".postal-code", this).text();
            var lat = $(".latitude", this).text();
            var lon = $(".longitude", this).text();

            var loc = new VELatLong(lat, lon);
            try {
                var pin = new VEPushpin(counter, loc, 'http://secure.jacksonhewitt.com/App_Themes/Default/images/JacksonHewittLogoIcon.gif', 'Jackson Hewitt Tax Service <br/>' + address + '<br />' + city + ' ' + state + ', ' + zip, '');
                map.AddPushpin(pin);
            }
            catch (err) { }

            counter++;
        }
    });
}


$(document).ready(function() {

    // Setting up tabs
    var tabContainers = $('div#office_info > div.tabbed_container');
    $('div#office_info ul.tabs a').click(function() {
        tabContainers.hide().filter(this.hash).show();
        $('div#office_info ul.tabs a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();

    var tabContainersAlt = $('div#office_details > div.tabbed_container');
    $('div#office_details ul.tabs a').click(function() {
        tabContainersAlt.hide().filter(this.hash).show();
        $('div#office_details ul.tabs a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();

    // Prepping list toggles and shadowboxes
    //    about_jh = $('#aboutjhtx > div:first-child');
    //    about_jh.attr('id', 'about_jh');
    //    about_jh.children().each(function(i) { $(this).replaceWith("<p>" + $(this).text() + "<\/p>"); });

    //    exp_points = about_jh.next();
    //    exp_points.attr('id', 'exp_points');
    //    exp_points.children('li:empty').remove();
    //    exp_points.children('ul').wrap('<li />');

    fixlists('#moreabout > div:first-child');
    fixlists('#products > div:first-child', true);

    PrepList();


    

    $('#pnlDefaultDesc li').wrapInner('<span />');

    // Some IE6 fixes
    $("input[type='text']").addClass('ie_text_inputs text');

    // Form validation
    $("#col_right form").RSV({
        onCompleteHandler: null,
        errorFieldClass: "error",
        rules: [
			"required,fname,Please enter your first name.",
			"required,lname,Please enter your last name.",
			"required,email,Please enter your email address.",
			"valid_email,email,Please enter a valid email address.",
			"required,postal,Please enter your zip code.",
			"digits_only,postal,Please enter a valid postal code."
		]
    });

    $("#new_zip_search").RSV({
        onCompleteHandler: newZipSearch,
        errorFieldClass: "error",
        rules: [
			"required,zip,Please enter a zip code.",
			"digits_only,zip,Please enter a valid zip code."
		]
    });


    $("#nextpg").click(function() {
        if (currpage < maxpages) {
            currpage++;
            setPage();
        }
        return false;
    });

    $("#prevpg").click(function() {
        if (currpage > 1) {
            currpage--;
            setPage();
        }
        return false;
    });

    $("#zipsearchbtn").click(function() {

        window.location.href = "/officelist.aspx?searchby=zip&searchfor=" + $("#txtzip").val();

    });


    $("#txtzip").keypress(function(e) {
        var unicode = e.which ? e.which : e.keyCode;

        if (unicode != 8) { //backspace key
            if (unicode < 48 || unicode > 57) { //trap the key press
                if (unicode == 13) {
                    window.location.href = "/officelist.aspx?searchby=zip&searchfor=" + $("#txtzip").val();
                }
                else {
                    return false;
                }
            }
        }
        return true;
    });

    // Prepping maps
    GetMap();

    $('a.terms').click(function() {
        window.open($(this).attr('href'), 'terms', 'width=400,height=400,resizable=yes,menubar=no,toolbar=no,titlebar=no,scrollbars=yes', false);
        return false;
    });

    $('p.submit_image input').mouseover(function() {
        $(this).attr('src', '/img/button-download_over.gif');

    });

    $('p.submit_image input').mouseout(function() {
        $(this).attr('src', '/img/button-download.gif');
    });





});

function centerOffice(lat, lon) {
    try {
        map.SetCenterAndZoom(new VELatLong(lat, lon), 15);
    } catch (err) {
        alert(err.description);
    }
}

function isTermsChecked(sender, args) {
    if ($('.terms_checkbox input').attr('checked')) {

        args.IsValid = true;

    }
    else {
        args.IsValid = false;

    }
}

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

function js_gaaw_track() {
    var current_path = document.location.pathname;
    pageTracker._trackEvent('download_form', 'submit', current_path);
    pause(1000);
}

function ValidateAndTrack() {

    Page_ClientValidate();
    if (Page_IsValid) {
        js_gaaw_track();
        return true;
    }
    else {
        return false;
    }
}
