

if (typeof (TD) == 'undefined')
    var TD = {};

TD.ProjectStarter = {


    //Time Since Function

    TimeSincePublished: function (tsclass, sysdate, displaytext, predicate, maxsecondsOverride) {
        var curdate, pubdate;
        var days, hours, minutes;
        var timetext;
        var timespans;
        var difference;
        var predicateString, timestampstring;
        var maxseconds = maxsecondsOverride || 90000000000000000;
        var SECONDS = {
            DAY: 24 * 60 * 60,
            HOUR: 60 * 60,
            MIN: 60
        }

        //if latest isnt set already then try loading it
        /* 
        // 2009-10-16: Commented out because this is taking a long time to process. 
        // Takes up between 25+% of total js execution time
        if (!TD.ProjectTheStar.latest) {
        TD.ProjectTheStar.latest = TD.ProjectTheStar.readHTTPHeaders("/js/TD.js?" + Math.random() * 5000);
        }

        if (TD.ProjectTheStar.latest.length > 1) {
        curdate = new Date(TD.ProjectTheStar.latest);
        } else {
        curdate = new Date(sysdate);
        }
        */

        curdate = new Date((sysdate.length > 1) ? sysdate : Date());

        //find all spans with tsclass
        timespans = $('span.' + tsclass);
        for (var i = 0; i < timespans.length; i++) {
            timespan = jQuery(timespans[i]);

            timetext = timespan.html().replace(/^\s*(\S*(\s+\S+)*)\s*$/, '$1');
            if (!timetext) return;

            pubdate = new Date(timetext);
            difference = curdate.getTime() - pubdate.getTime();
            difference = difference / 1000;
            if (difference <= maxseconds && difference > 0) {
                days = Math.floor(difference / SECONDS.DAY);
                hours = Math.floor((difference - (days * SECONDS.DAY)) / SECONDS.HOUR);
                minutes = Math.floor((difference - (days * SECONDS.DAY) - (hours * SECONDS.HOUR)) / SECONDS.MIN);
                if (days || hours || minutes) {
                    predicateString = (!!displaytext) ? displaytext + " " : "";
                }

                if (days > 0) {
                    timestampstring = (!!days) ? days + " day" + (days > 1 ? "s" : "") + " " : "";
                }
                else if (hours > 0) {
                    timestampstring += (!!hours) ? hours + " hour" + (hours > 1 ? "s" : "") + " " : "";
                }
                else if (minutes > 0) {
                    timestampstring += (!!minutes) ? minutes + " minute" + (minutes > 1 ? "s" : "") + " " : "";
                }
                if (days || hours || minutes) {
                    timespan.html(predicateString + timestampstring + "ago");
                    timespan.addClass('td-red');
                }
                timestampstring = "";
            } else {
                if (difference > maxseconds) {
                    predicateString = "";
                    if (displaytext != '')
                        predicateString = displaytext + " ";
                    if (predicate != '')
                        predicateString += predicate + " ";
                    timespan.html(predicateString + pubdate.toDateString());
                }
                else {
                    timespan.html('');
                }
            }
            timespan.removeClass('td-hidden_block');
        };
    },


    //Search Input
    TopSearchType_Click: function (sender, e) {
        $('#TopSearchType')[0].value = e;
        $('.td_search_links a').removeClass("td_active");
        $(sender).addClass("td_active");
        return false;
    },
    TopSearchType_InputPress: function (event) {
        if (!TD.Forms.IsPressedEnter(event))
            return true;
        TD.ProjectStarter.TopSearchGo_Click();
        return false;
    },
    TopSearchGo_Click: function () {
        var tt = $('#TopSearchValue')[0];
        if ($('#TopSearchValue')[0].value == '')
            return;
        document.location = "/search?q=" + escape($('#TopSearchValue')[0].value) + '&r=all:1';
    },

    CheckUserAvailability: function (UserName, Id) {
        var reg = /^(\w){3,}$/;
        if (!(reg.exec(UserName))) {
            $('#' + Id)[0].innerHTML = '';
            return;
        }

        $.get('/toplets/login/ValidateUser.ashx?user=' + UserName,
		function (data) {
		    var expression = '#' + Id;
		    $(expression)[0].innerHTML = data;
		    if (data.indexOf("Yes") != -1) {
		        $(expression).removeClass("red");
		        $(expression).addClass("green");
		    }
		    else {
		        $(expression).removeClass("green");
		        $(expression).addClass("red");
		    }
		});
    },
    IncreaseFontSize: function (selector, size) {
        var fontSize = $(selector).css("fontSize");
        $(selector).css("fontSize", size);
    },

    DecreaseFontSize: function (selector, size) {
        var fontSize = $(selector).css("fontSize");

        $(selector).css("font-size", size + "px");
    },
    Search: {
        Refine: function (keyword) {
            var q = (keyword || "");

            var r = [];
            r.push($(".td_search_refine_category :checked").map(function () {
                return encodeURIComponent("FullCategory:\"" + $(this).val() + "\"");
            }).get().join(" AND "));

            r.push($(".td_search_refine_author :checked").map(function () {
                return encodeURIComponent("Author:\"" + $(this).val() + "\"");
            }).get().join(" AND "));

            r.push($(".td_search_refine_date li:has(.radio-checked)").map(function () {
                return encodeURIComponent("PublishDate:" + $(this).find(":radio").val());
            }).get().toString());

            var dates = $(".td_search_refine_date .js-datepicker").map(function () {
                var date = $(this).val().split("/");
                if (date.length < 3) return;
                return [date[2], date[0], date[1]].join("");
            }).get().sort().join(" TO ");

            if (!!dates) {
                if (/\d{8}\sTO\s\d{8}/.test(dates)) {
                    r.push(encodeURIComponent("PublishDate:[" + dates + "]"));
                } else if (/\d{8}/.test(dates)) {
                    r.push(encodeURIComponent("PublishDate:" + dates));
                }
            }


            var assetType = $(".td_search_refine_assettype :checked").map(function () {
                return $(this).val();
            }).get().join(",");

            location.search = "atype=" + assetType + "&q=" + q + "&r=" + $.grep(r, function (n) { return $.trim(n); }).join(' AND ');
        }
    },

    Horoscopes: {
        "setMySign": function () {
            var sign = $(".js-horoscope-sign").html().toLowerCase();
            TD.Framework.WriteCookie("horoscopeSign", sign, 2160);
            TD.ProjectStarter.Horoscopes.refresh();
        },
        "unsetMySign": function () {
            TD.Framework.WriteCookie("horoscopeSign", null, -1);
            TD.ProjectStarter.Horoscopes.refresh();
        },
        "redirect": function () {
            var mySign = (TD.Framework.ReadCookie("horoscopeSign") || "").toLowerCase();
            var regex = new RegExp(mySign, "i");
            var regexSubPage = new RegExp("/horoscopes/\\w+", "i");
            if (mySign && !regex.test(location.pathname) && !regexSubPage.test(location.pathname)) {
                location.replace("/en/living/horoscopes/" + mySign);
            }
        },
        "refresh": function () {
            var mySign = (TD.Framework.ReadCookie("horoscopeSign") || "").toLowerCase();
            var sign = $(".js-horoscope-sign").html().toLowerCase();

            if (sign === mySign) {
                $(".js-toggle .js-toggle_set").hide();
                $(".js-toggle .js-toggle_unset").show();
            } else {
                $(".js-toggle .js-toggle_unset").hide();
                $(".js-toggle .js-toggle_set").show();
            }
        }
    }

    //    IncreaseFontSize: function(selector) {
    //        var fontSize = $(selector).css("fontSize");
    //        var unit = fontSize.match(/\D*$/)[0];
    //        var size = parseFloat(fontSize);

    //        var max = { "px": 20, "em": 2, "%": 200 }
    //        var step = { "px": 1, "em": .1, "%": 10 }
    //        if (size > max[unit]) return;
    //        $(selector).css("fontSize", (size + step[unit]) + unit);
    //    },

    //    DecreaseFontSize: function(selector) {
    //        var fontSize = $(selector).css("fontSize");
    //        var unit = fontSize.match(/\D*$/)[0];
    //        var size = parseFloat(fontSize);

    //        var min = { "px": 10, "em": 1, "%": 100 }
    //        var step = { "px": -1, "em": -.1, "%": -10 }
    //        if (size < min[unit]) return;
    //        $(selector).css("fontSize", (size + step[unit]) + unit);
    //    }
}

