jQuery(document).ready(function()
{
	BCHomes.initForms ();
	BCHomes.initTagAndCatLinks ();
	BCHomes.initBlogTitleAndAuthor ();
	BCHomes.initMenu ();
	BCHomes.paginateArticle ();
	BCHomes.removeGoBackLinks ();
	BCHomes.fixSiteFinityBugs ();
	BCHomes.fixTagsPageUrlMappings ();
	BCHomes.collapsiblePastColumnYears ();
	BCHomes.filterColumnPastIssues ();
	
	BCHomes.contestMailtoUrl();
	BCHomes.contestFindFirstError();
	
	BCHomes.subscriptionForm();
	BCHomes.subscriptionDisableCCButton();
});

var BCHomes = {
    path: "/", //"/bchomesmag/",
    test: "",

    initForms: function () {
        // Remove the Login link in the Login/Logout control form.  It will automatically
        // display the login form if we are logged in.
        var input = jQuery("div#login-status a");
        if (input.length != 0 && input.html() == "Logout")
            input.show();

        for (var i = 0; i < 2; i++) {
            if (i == 0)
                input = jQuery("div#login-form div.login-col-username input[type='text']");
            else if (i == 1)
                input = jQuery("div#login-form div.login-col-password input[type='password']");
            else
                input = jQuery("form#search-form input[name='s']");

            input.bind('focus', function (e) {
                if (!jQuery(this).attr('visited'))
                    this.value = '';

                jQuery(this).attr('visited', true);
            });

            input.bind('blur', { i: i }, function (e) {
                if (this.value == '') {
                    if (e.data.i == 0)
                        this.value = 'Username';
                    else if (e.data.i == 1)
                        this.value = 'Password';
                    else
                        this.value = 'Search';
                    jQuery(this).removeAttr('visited');
                }
            });
        }
    },

    initBlogTitleAndAuthor: function () {
        var blogTitle = jQuery("#content #content-middle div.column-body div.sf_singlePost h1.sf_postTitle,#content #content-middle div.feature-body div.sf_singlePost h1.sf_postTitle");
        var blogSubTitle;
        // Do not get the img if it is wrapped in an h5 tag.
        jQuery("#content #content-middle div.column-body div.sf_singlePost h5,#content #content-middle div.feature-body div.sf_singlePost h5").each(function () {
            if ($(this).html().indexOf("<img") == -1) {
                blogSubTitle = $(this);
                return false;
            }
        });
        var blogAuthor = jQuery("#content #content-middle div.column-body div.sf_singlePost p.sf_postAuthor,#content #content-middle div.feature-body div.sf_singlePost p.sf_postAuthor");
        var blogAuthorStripped = jQuery("#content #content-middle div.column-body div.sf_singlePost p.sf_postAuthor a,#content #content-middle div.feature-body div.sf_singlePost p.sf_postAuthor a");
        var pageTitle = jQuery("#content #content-middle div.page-title");
        var pageSubTitle = jQuery("#content #content-middle h5.page-sub-title");
        var pageAuthor = jQuery("#content #content-middle div.author");
        var pageAuthorPic = jQuery("#content #content-middle div.author-pic");

        if (blogTitle.length != 0)
            pageTitle.html(blogTitle.html());

        if (blogSubTitle && blogSubTitle.length != 0) {
            pageSubTitle.html(blogSubTitle.html());
            blogSubTitle.html("");
        }

        if (blogAuthor.length != 0) {
            // If columns then show the author above the post.
            if (jQuery("#content #content-middle div.column-body").get(0) &&
				!jQuery("#content #content-middle div#insite-header").get(0)) {
                pageAuthor.hide();
                jQuery("#content #content-middle div.column-body div.sf_singlePost p.sf_postAuthor a").before("By ");
                jQuery("#content #content-middle div.column-body div.sf_singlePost p.sf_postAuthor").show();

                // Find the blog name and display it at the top.
                jQuery("#content #content-middle div.column-body p.sf_postTags a").each(function () {
                    var tag = $(this).html();
                    if ((tag == "Bon Vivant") || (tag == "Developments") ||
						(tag == "Going to Market") || (tag == "Outside Looking In") ||
						(tag == "Perspectives"))
                        jQuery("#content #content-middle div.blog-title").html(tag);
                });
            }
            else {
                pageAuthor.html("By " + blogAuthor.html().replace("Posted by:", ""));
            }

            var img = BCHomes.path + "Libraries/Authors/" +
				blogAuthorStripped.html().trim().toLowerCase().replace(/ /g, "-").replace(/\./g, "_") + ".tmb.ashx";
            pageAuthorPic.css("background-image", "url(" + img + ")");
            /*				
            $.ajax({
            url: img,
            type:'HEAD',
            error:
            function(){
            alert ("fail");
            pageAuthorPic.hide ();
            },
            success:
            function(){
            alert ("success");
            }
            });*/
        }
    },

    initMenu: function () {
        var path = document.location.pathname;
        var sa = path.split("/", 3);

        for (var i = 1; i < sa.length; i++) {
            var s = sa[i].split(".", 1);
            s = s[0].toLowerCase();

            if (s == "feature" || s == "column")
                s += "s";

            var menu = jQuery("#content ul#menu li." + s + " a");
            if (menu.length != 0) {
                menu.addClass("active");
                break;
            }
        }
    },

    initTagAndCatLinks: function () {
        // Change the category and tag links to go to the Tags.aspx page.
        jQuery("p.sf_postTags a, p.sf_postCategory a").each(function () {
            this.href = this.href.replace("column.aspx", "Tags.aspx");
            this.href = this.href.replace("columns.aspx", "Tags.aspx");
            this.href = this.href.replace("features.aspx", "Tags.aspx");
            this.href = this.href.replace("feature.aspx", "Tags.aspx");
            this.href = this.href.replace("insite.aspx", "Tags.aspx");
            this.href = this.href.replace("insitearticle.aspx", "Tags.aspx");
        });

        // Add commas for tag separation.
        jQuery("p.sf_postTags").each(function () {
            $(this).html($(this).html().replace(/(\/a>)(\s+<a)/g, "$1, $2"));
        });

        // Find the author tags and convert them to Tags.aspx
        jQuery("ul li.activeBlogger a, p.sf_postAuthor a").each(function () {
            var s = BCHomes.getAuthorCSSName($(this).html());

            if (s != "") {
                var tagID = jQuery("div#author-tag-ids p." + s);
                if (tagID.length != 0) {
                    this.href = this.href.replace("Column.aspx", "Tags.aspx?BlogTagID=" + tagID.html());
                    this.href = this.href.replace("Columns.aspx", "Tags.aspx?BlogTagID=" + tagID.html());
                    this.href = this.href.replace("Features.aspx", "Tags.aspx?BlogTagID=" + tagID.html());
                    this.href = this.href.replace("Feature.aspx", "Tags.aspx?BlogTagID=" + tagID.html());
                }
            }
        });
    },

    paginateArticle: function () {
        var body = jQuery("div.feature-body div.sf_singlePost div.sf_postContent");
        if (body.length != 0) {
            var re = new RegExp(/(<img[^>]*\>)/);
            var text = body.html();
            var paragraphs = text.split("<p>");
            var pageText = "";
            var newText = "";
            var pagination = "";
            var currentPage = BCHomes.getUrlVar("p");
            var firstImg = "";
            var n = 1;
            //alert (location.pathname);

            if (currentPage != undefined && BCHomes.isInteger(currentPage))
                currentPage = parseInt(currentPage);
            else
                currentPage = 1;
            if (currentPage == 0)
                currentPage = 1;
            //alert (currentPage);

            // Turn off the page title and subtitle if this is not page 1.
            if (currentPage != 1) {
                jQuery("#content #content-middle div.page-title").hide();
                jQuery("#content #content-middle h5.page-sub-title").hide();
            }

            //alert (paragraphs.length);			
            for (var i = 0; i < paragraphs.length; i++) {
                //alert (paragraphs[i].length);			
                if (i != 0)
                    pageText += "<p>";

                // Grab the top img.
                var m = re.exec(paragraphs[i]);
                if (firstImg == "" && m != null && m.length > 0)
                    firstImg = m[0];
                //alert (firstImg);
                pageText += paragraphs[i];
                if (pageText.length > 4000) {
                    //alert (pageText);
                    // Add the page text to this page div.
                    // Add the top img if we are not on page 1.
                    newText += "<div id=\"article-page-" + n + "\" style=\"display: none;\">" +
                    /*((n != 1)? firstImg : "") + */pageText + "</div>";
                    pagination += "<li>" +
						((currentPage == n) ? n : "<a href=\"" + location.pathname + "?p=" + n + "\">" + n + "</a>") +
						"</li>";
                    pageText = "";
                    n++;
                }
            }

            if (pageText != "") {
                newText += "<div id=\"article-page-" + n + "\" style=\"display: none;\">" +
                /*((n != 1)? firstImg : "") + */pageText + "</div>";
                pagination += "<li>" +
					((currentPage == n) ? n : "<a href=\"" + location.pathname + "?p=" + n + "\">" + n + "</a>") +
					"</li>";
            }

            if (currentPage > n)
                currentPage = n;

            // If there is more than one page then hide the original page and show the current page div.
            if (n > 2) {
                // Add the pagination links.
                pagination = "<ul><li>Page:</li>" + pagination + "</ul><div class=\"clear\"></div>";
                newText += "<div id=\"article-pagination-links\">" + pagination + "</div>";

                //			body.append (newText);
                //BCHomes.test = newText;
                body.html(newText);
                //alert (currentPage);
                // Find the current page number and enable that page div.
                jQuery("div#article-page-" + currentPage).show();

                // Add the pagination to the top of the page as well.
                jQuery("div#pagination-links-top").html(pagination);
            }
        }
    },

    fixSiteFinityBugs: function () {
        // Pretty in pink search is pointing to news instead of blogs.
        jQuery("ul.sf_searchResults a").each(function () {
            //alert (this.href);
            if (this.href.indexOf("/News/10-04-07/Next_Big_Thing_Pretty_in_Pink.aspx") != -1)
                this.href = "/Features/10-04-07/Next_Big_Thing_Pretty_in_Pink.aspx";
        });
    },

    fixTagsPageUrlMappings: function () {
        var i = 0;

        jQuery("ul.sf_postListing li a").each(function () {
            var s = this.href.replace(/http:\/\/[A-z\.]*bchomesmag\.com\//, "");
            s = s.replace(/\//g, "_");
            s = s.replace(".", "_");
            var sa = s.split("#");
            if (sa.length > 0)
                s = sa[0];
            if (i++ == 0)
                ; //alert (s);
            var e = jQuery("ul#tag-url-mappings li." + s);
            if (e != null && e.html() != null && e.html().length > 0)
                this.href = e.html() + ((sa.length > 1) ? "#" + sa[1] : "");
        });
    },

    collapsiblePastColumnYears: function () {
        var i = 0;

        jQuery(".past-features ul.past-columns li.past-columns").each(function () {
            // Skip the first year.
            if (i++ == 0)
                ; // return true;
            var s = $(this).html();
            s = s.replace(/(\d{4})/, '<a href="#" onclick="return BCHomes.collapseYear(\'$1\');">$1</a>');
            //	alert (s);
            $(this).html(s);
        });
    },

    collapseYear: function (year) {
        jQuery(".past-features ul.past-columns li.year-" + year + " ul").toggle(200);
        return false;
    },

    filterColumnPastIssues: function () {
        if (jQuery("#content #content-middle div.column-body").get(0) &&
			!jQuery("#content #content-middle div#insite-header").get(0)) {
            var blogName = jQuery("#content #content-middle div.blog-title").html();
            //			alert (blogName);
            blogName = blogName.replace(/ /g, "-").replace(/\./g, "_");

            // Hide any past issues that do not belong to this current blog container.
            // Only get the top level li children else it will grab the li items in the nested ul as well.
            jQuery(".past-features ul.past-columns li.past-columns ul.sf_genericContentList_issues").children("li").each(function () {
                //alert ($(this).html());
                var cnt = 0;

                $(this).find("ul.sf_genericContentList_articles li a").each(function () {
                    //alert (this.className + ", " + blogName);
                    if (this.className != blogName)
                         $(this).parent().hide();
                    else
                        cnt++;
                });

                if (cnt == 0)
                    $(this).hide();
            });

        }
    },

    // Change the Send To Friend mailto: link to the proper contest URL on
    // the contest popup form.
    contestMailtoUrl: function () {
        jQuery("#template-contest a").each(function () {
            if (!this.href.match(/^mailto\:/))
                return true;

            var url = location.href.replace(/(.*\?id=[0-9]*).*/, "$1");
            this.href = this.href.replace("_URL_", url);
        });
    },

    contestFindFirstError: function () {
        // Find the first visible ASP error span tag.
        jQuery("#template-contest .contest-form td span,.subscription-form li span").each(function () {
            // Our ASP validator tags have "_v" in the name.
            if (($(this).css("visibility") == "hidden") ||
				!$(this).attr("id").match(/_v/))
                return true;

            //			alert ($(this).attr("id") + ", " + $(this).css("color") + ", " + $(this).css("visibility"));

            var e = $(this).parent().find("input");
            $.scrollTo($(this).parent(), 500, { onAfter: function () { e.focus(); } });
            //			$(this).parent().find("input").focus();

            return false;
        });
    },

    contestScrollToErrorForIE: function () {
        if (!Page_ClientValidate()) {
            BCHomes.contestFindFirstError();
        }
        return false;
    },

    subscriptionForm: function () {
        jQuery(".subscription-landing-form .fields input[type=text]").click(function () {
            var uid = this.name.replace("SubscriptionRenewID", "");
            uid = uid.replace("PromoCode", "");
            uid = uid.replace(/\$/g, "_");
            //alert(uid);
            if (this.name.indexOf("RenewID") != -1)
                jQuery(".subscription-landing-form .fields #" + uid + "RadioButton2").attr("checked", true);
            else if (this.name.indexOf("PromoCode") != -1)
                jQuery(".subscription-landing-form .fields #" + uid + "RadioButton3").attr("checked", true);
        });

        if (jQuery(".subscription-billing-header input[type=checkbox]:checked").val() == null)
            jQuery(".subscription-form ul.subscription-billing").hide();
        else
            jQuery(".subscription-form ul.subscription-billing").show();

        jQuery(".subscription-billing-header input[type=checkbox]").click(function () {
            jQuery(".subscription-form ul.subscription-billing").toggle(300);
        });
    },

    subscriptionDisableCCButton: function () {
        jQuery(".subscription-form input[type=submit]").click(function () {
            /*
            if ((typeof(Page_IsValid )!="undefined")&&(Page_IsValid == false))
            {
            return false;
            }
            else
            {
            $(this).attr("disabled", "true");
            $(this).val("Processing...");
            return true;
            }*/
            return false;
        });
    },

    removeGoBackLinks: function () {
        jQuery("a").filter(function () { return this.id.match(/backLink/); }).each(function () {
            //			alert ('hi');
            $(this).hide();
        });
    },

    getAuthorCSSName: function (name) {
        return name.trim().toLowerCase().replace(/ /g, "-").replace(/\./g, "_");
    },

    isInteger: function (s) {
        return (s.toString().search(/^-?[0-9]+$/) == 0);
    },

    getUrlVar: function (parm) {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars[parm];
    }

}


