var results = [];
var pageItems = 10;
var bgEnterTarget = "";

var numpages = 1;

var method = "";
var qry = "";
var cat = "";


$(document).ready(function() {
    setupServicesandIndustries();
    initMainNavigation();


    //Remove "Newsletters" nav items
    //jQuery('li a:contains(\'Newsletters\')').parent().css('display', 'none');

    //Remove January 20th Blog Article
    jQuery('table.calendarTable tr.weekRow td a:contains(\'20\')').css('text-decoration', 'none').css('color', '#5F6168').parent().removeClass('activeDay').addClass('inactiveDay');

    clearSearch();

    //Init Modals
    initContactModals();
    initSEOBar();
    initAboutUsRows();
    //initCommonRoundedCorners();

    //var clHTML = $(".pageCopyWrapper").html().replace(/<p>&nbsp;<\/p>/g, ' ');
    //$(".pageCopyWrapper").html(clHTML);
    //document.body.innerHTML=document.body.innerHTML.replace(/<p>&nbsp;<\/p>/g,' ');

    $('input').keypress(function(event) {
        if (event.which == '13') {
            event.preventDefault();
            $(this).nextAll(":submit").click();
            $(this).siblings(":submit").click();
            $(this).parent().siblings().children(":submit").click();
        }
    });

    /*
    if ($.browser.msie) {
    $("div.buttonSendAMessage").css('display', 'none !important');
    }
    */
    collapseSecondaryNav();

    initNewsletterSubmit();

    $('a[href="http://www.eisnerampertaxguide.com/"],a[href="http://eisneramper.silkroad.com"]').attr("target", "_blank");

    var rightCol = $(".rightColContent");
    if (rightCol.find("#ctl00_ContentPlaceHolder1_relatedLinksPanel > span, #ctl00_pageHostHolder_relatedLinksPanel > span").length > 2) {
        rightCol.show();
    }

    //SEO Bar Rounded Corners
    initRoundedCorners(5, "#seoBarContainer");

    $('.johndoe').focus(function() {
        if ($(this).attr("value") == "johndoe@email.com")
            $(this).attr("value", "");
    });





});


// Collapsable Secondary Nav
function collapseSecondaryNav() {

    // Initial Hide
    $(".leftColWrapper ul.secondaryNav li ul").hide();

    // Show pinned content

    if ($(".leftColWrapper ul.secondaryNav li.pinned ul li").length > 0) {
        $(".leftColWrapper ul.secondaryNav li.pinned").children("ul").show();
    }
    $(".leftColWrapper ul.secondaryNav li ul li.pinned").parent("ul").show();
    $(".leftColWrapper ul.secondaryNav li ul li ul li.pinned").parent("ul").show();
    $(".leftColWrapper ul.secondaryNav li ul li ul li.pinned").parent("ul").parent("li").parent("ul").show();

    // Show pinned content
    //$(".leftColWrapper ul.secondaryNav li ul li.pinned ul").show();


    /*
    // Toggle visible on click
    $("ul.secondaryNav li").click(function(event) {

			// Prevent going to a new page.
    // Comment this line out if you want top level linking
    //event.preventDefault();
			
    target = $(this).children('ul');
			
    // Toggle visibility 
    if (target.is(':visible')) {
    target.slideUp();
    } else {
    target.slideDown();
    }
    });
    */
}

// focusEl : Jquery Selector Text for the input fields 
// targetEl: Jquery Selector Text for the submit button those fields trigger
function setEnterTargetOnFocus(focusEl, targetEl) {
    $(focusEl).focus(function() {
        bgEnterTarget = targetEl;
    })
}



function initVideos() {
    $("a[href*=.flv], a[href*=.mp4]").flowplayer("/includes/swf/flowplayer.commercial-3.2.5-1.swf",
	{
	    key: '$571a10a784775ba3747',
	    logo: null,
	    clip: {
	        autoPlay: false,
	        autoBuffering: true,
	        scaling: 'orig'
	    }
	});
}



function clearSearch() {
    if ($('.globalSearchInput').length > 0) {
        $(".globalSearchInput").bind('click', function() {
            var value = $(this).val();
            if (value == 'search') {
                $(this).val('');
            }
        });
    }
}






function initSEOBar() {
    var pageTitle = $("#ctl00_ContentPlaceHolder1_pageTitle").html();
    $("#ctl00_pageHostHolder_relatedLinksPanel ul li a").each(function(i) {
        if ($(this).html() == pageTitle) {
            $(this).parent().remove();
        }

    });


    if ($('#hiddenRight').length > 0) {
        $('#rightTarget').append($('#hiddenRight').html());

        //SEO Bar Corners
        initRoundedCorners(5, '#SEOBarTarget,#seoBarContainer');
        //initRoundedCorners(5, "#seoBarContainer");

    }
}




function initAboutUsRows() {
    /*
    if ($('.aboutUsPage').length > 0){
    $('.aboutUsPage p:even').addClass('bubbleParagraph boxWrapper');
    //About Us Copy
    if(!jQuery.browser.msie){
    initRoundedCorners(10, ".bubbleParagraph");
    };
		
	}
    */
}



function modalBioShowForm() {
    //$('#modalContactBioFormWrapper').slideDown('slow');
    $('#modalContactBioFormWrapper').slideDown('slow');

    $('.modalBoxWrapper').animate({ scrollTop: '600px' }, 500);


}




function fontResizer(val) {
    // 1 = reset font to 12px
    // 2 = reset font to 13px
    // 3 = reset font to 14px
    switch (val) {
        case 1:
            $('.pageCopyWrapper p').css('font-size', '12px');
            resetPageHeight();
            break;
        case 2:
            $('.pageCopyWrapper p').css('font-size', '1.2em');
            resetPageHeight();
            break;
        case 3:
            $('.pageCopyWrapper p').css('font-size', '1.3em');
            resetPageHeight();
            break;
        default:
            $('.pageCopyWrapper p').css('font-size', '12px');
            resetPageHeight();
            break;
    }
}



function initContactModals() {
    $('a.nyroModal').nyroModal();
}

function initCommonRoundedCorners() {

    //Modal Dialogs
    initRoundedCorners(10, ".modalBoxWrapper");
    // Primary Contact Container
    initRoundedCorners(5, ".primaryContactContainer");

}

function initRoundedCorners(radVal, elem) {
    $(function() {
        settings = {
            tl: { radius: radVal },
            tr: { radius: radVal },
            bl: { radius: radVal },
            br: { radius: radVal },
            antiAlias: true,
            autoPad: true,
            validTags: ["div"]
        }
        $(elem).corner(settings);
    });
}



/* pagination code */
function pageselectCallback(pageIndex, jq) {
    var max = Math.min((pageIndex + 1) * pageItems, results.length);
    var newContent = "";
    for (var i = pageIndex * pageItems; i < max; i++) {
        newContent += "<div class='listItem'>";
        newContent += results[i];
        newContent += "</div>";
    }
    $('#result').empty().append(newContent);
    return false;
}



function initPagination() {
    results = [];
    var listedItems = $('#hiddenResult div.listItem,#hiddenResult div.videoListItem');
    listedItems.each(function() { results.push($(this).html()) })
    var numEntries = listedItems.length;
    $("#pagination").pagination(numEntries, {
        callback: pageselectCallback,
        items_per_page: pageItems,
        prev_text: "<< Previous",
        next_text: "Next >>",
        next_show_always: false,
        prev_show_always: false
    });
}
function AjaxPageSelectCallback(idx) {

    $("#pagination a.page").removeClass("current");

   

    $("#result").html("<div style='text-align:center'><img src='/includes/images/round-ajax-loader.gif' /></div>");
   
    $.get("/handlers/ArticleListHandler.ashx",
                    {
                        action: method,
                        pagenum: idx,
                        query: qry,
                        category: cat
                    },
                    function(data) {
                    
                        
                        $("#result").html(data);
                        
                        DoPagingWindow(idx);
                        window.scrollTo(0, $('#results').offset.top);
                    });
    if (idx == 1) {
        $("#pagination a.prev").hide();
    } else {
        $("#pagination a.prev").show();
    }

    if (idx == numpages) {
        $("#pagination a.next").hide();
    } else {
        $("#pagination a.next").show();
    }

}

function initAjaxPagination(mmethod, pageItems, numEntries, mquery, mcategory) {

    qry = mquery;
    cat = mcategory;

    method = mmethod;

    numpages = Math.ceil(numEntries / pageItems);

    if (numpages > 0)  {
        var pagination = "<a href='#' class='prev' style='display:none'> &lt;&lt;Previous</a>";
        for (var i = 1; i <= numpages; i++) {
            pagination += "<a href='#' class='page"
            if (i == 1) pagination += " current";
            pagination += "'>" + i + "</a>";
        }
       if (numpages > 1)
            pagination += "<a href='#' class='next'>Next &gt;&gt;</a>";

        $("div#pagination").html(pagination);

        DoPagingWindow(1);
    }
/* events */
    $("div#pagination a.page").live('click', function(e) {
        e.preventDefault();

        AjaxPageSelectCallback($(this).text());


    });
    $("div#pagination a.prev").live('click', function(e) {
        e.preventDefault();
        var current = $("div#pagination a.page.current");
        if ($(current).text() >= 2) {


            AjaxPageSelectCallback($(current).prev().text());


        }
    });
    $("div#pagination a.next").live('click', function(e) {
        e.preventDefault();
        var current = $("div#pagination a.page.current");
        if ($(current).text() < numpages) {
            AjaxPageSelectCallback($(current).next().text());


        }
    });
}


function DoPagingWindow(idx) {
    var start = Math.max(1, idx - 10);

    var stop = Math.max(20,parseInt(idx) + 10);
    
    
    
    $('#pagination a.page').each(function() {

        var currpage = $(this).text();

        if ((currpage < (start)) || (currpage > (stop))) {
            $(this).hide();
        }
        else {
            $(this).show();
        }

        if (currpage == idx) {
            $(this).addClass("current");
        }
        else {
            $(this).removeClass("current");
        }

    });
}


// Retired/refactored methods

function resetPageHeight() {

    //var ht1 = Math.max(parseInt($('.rightColWrapper').css('height'), 10), parseInt($('.leftColWrapper').css('height'), 10), parseInt($('.pageCopyWrapper').css('height'), 10)); 
    /*	
    var htRight = parseInt($('.rightColWrapper').css('height'), 10);
    var htLeft = parseInt($('.leftColWrapper').css('height'), 10);
    var htCenter = parseInt($('.pageCopyWrapper').css('height'), 10);
	
    if (isNaN(htRight)){
    alert(htRight);
    var htRight	= parseInt(400, 10);
    }
    if (isNaN(htLeft)){
    alert(htLeft);
    var htLeft	= parseInt(400, 10);
    }
    if (isNaN(htCenter)){
    alert(htCenter);
    var htCenter = parseInt(400, 10);
    }
	
    var ht1 = Math.max(htRight, htLeft, htCenter);
	
	
    $('.pageContents').css('height', ht1);
    */
}

function setupServicesandIndustries() {
    $("#services-dropdown div.sub").append("<ul class='two secondaryNav'></ul><ul class='three secondaryNav'></ul><ul class='four secondaryNav'></ul>");
    $("#industries-dropdown div.sub").append("<ul class='two secondaryNav'></ul><ul class='three secondaryNav'></ul>");

    $("#services-dropdown div.sub ul.two").append($("#services-dropdown div.sub ul.secondaryNav > li").slice(8));
    $("#services-dropdown div.sub ul.three").append($("#services-dropdown div.sub ul.secondaryNav > li").slice(9));
    $("#services-dropdown div.sub ul.four").append($("#services-dropdown div.sub ul.secondaryNav > li").slice(11));

    $("#industries-dropdown div.sub ul.two").append($("#industries-dropdown div.sub ul.secondaryNav > li").slice(3));
    $("#industries-dropdown div.sub ul.three").append($("#industries-dropdown div.sub ul.secondaryNav > li").slice(7));

}



function initMainNavigation() {
    function megaHoverOver() {
        var target = $(this).find(".sub");
        var ht1 = target.height();
        //alert (ht1);
        if (ht1 < 200 && ht1 != null) {
            //alert('test');
            target.css('background-position', '0 0');
        } else {
            target.css('background-position', 'left bottom');
        }

        $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
        (function($) {
            //Function to calculate total width of all ul's
            jQuery.fn.calcSubWidth = function() {
                rowWidth = 0;
                //Calculate row
                $(this).find("ul.secondaryNav").each(function() { //for each ul...
                    rowWidth += ($(this).width() + 30); //Add each ul's width together
                    //alert(rowWidth);
                });
            };
        })(jQuery);

        if ($(this).find(".row").length > 0) { //If row exists...

            var biggestRow = 0;

            $(this).find(".row").each(function() {	//for each row...
                $(this).calcSubWidth(); //Call function to calculate width of all ul's
                //Find biggest row
                if (rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });

            $(this).find(".sub").css({ 'width': biggestRow }); //Set width
            $(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin


        } else { //If row does not exist...

            $(this).calcSubWidth();  //Call function to calculate width of all ul's
            $(this).find(".sub").css({ 'width': rowWidth }); //Set Width


            //var num1 = (rowWidth - 984)  * 3;
            //$(this).find(".sub").css({ 'left':  num1 }); 


        }
    }
    //On Hover Out
    function megaHoverOut() {
        $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
            $(this).hide();  //after fading, hide it
        });
    }

    //Set custom configurations
    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
        interval: 100, // number = milliseconds for onMouseOver polling interval
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
        timeout: 300, // number = milliseconds delay before onMouseOut
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)
    };

    $("ul#topnav li .sub").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default
    $("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations	
}

function initNewsletterSubmit() {

    $(".newslettersubmit").click(function(event) {
        event.preventDefault();

        window.location = "/newslettersubmit.aspx?email=&retURL=" + window.location;
        /*
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        
        $(this).prev().css("border-color", "black")
        var email = $(this).prev().val();
        if (reg.test(email)) {
        window.location = "/newslettersubmit.aspx?email=" + email + "&retURL=" + window.location;
        }
        else {
        $(this).prev().css("border-color", "red");
        }
        */

    });


}



