﻿if (typeof (TD) == 'undefined')
	var TD = {};

TD.ProjectTheStar = {
    latest: null,
    // TODO: set cookie domain to use the value below. 
    cookieDomain: window.location.hostname.replace(/www./, '.'),
    lastVisitCookieName: "UserLastLogin",

    TimeSincePublished2: 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 || 5400;
        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 = jQuery('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 + " " : "";
                    timestampstring = (!!days) ? days + " day" + (days > 1 ? "s" : "") + " " : "";
                    timestampstring += (!!hours) ? hours + " hour" + (hours > 1 ? "s" : "") + " " : "";
                    timestampstring += (!!minutes) ? minutes + " minute" + (minutes > 1 ? "s" : "") + " " : "";
                    timespan.html(predicateString + timestampstring + "ago");
                    timespan.addClass('td-red');
                }
            } 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');
        };
    },

    IsInFrame: function() {
        return !(window.top == window);
    },

    readHTTPHeaders: function(url) {
        var req = false;
        if (window.XMLHttpRequest && !(window.ActiveXObject)) {
            try {
                req = new XMLHttpRequest();
            } catch (e) {
                req = false;
            }
            // branch for IE/Windows ActiveX version
        } else if (window.ActiveXObject) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    req = false;
                }
            }
        }

        try {
            req.open('HEAD', url, false);
            req.send(null);
            return req.getResponseHeader("Date");
        }
        catch (e) {
            return "";
        }
    },

    CreateCookie: function(name, value, days) {

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/;";
    },

    ReadCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ')
                c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0)
                return c.substring(nameEQ.length, c.length);
        }
        return null;
    },

    RemoveCookie: function(name) {
        TD.ProjectTheStar.CreateCookie(name, '', -1);
    },

    setEventOmnitureArticleTab: function(Id, currentTab) {
        setTimeout(function() {
            var s = s_gi('thestarprod');
            s.linkTrackVars = "prop33,events";
            s.linkTrackEvents = "event1";
            s.prop33 = Id + "/" + currentTab;
            s.events = "event1";
            s.tl(this, 'o', 'Article Tab Click');
        }, 10);
    },
    setEventOmnitureTopicTab: function(Id, currentTab) {
        setTimeout(function() {
            var s = s_gi('thestarprod');
            s.linkTrackVars = "prop34,events";
            s.linkTrackEvents = "event2";
            s.prop34 = Id + "/" + currentTab;
            s.events = "event2";
            s.tl(this, 'o', 'Topic Tab Click');
        }, 10);
    },

    setEventOnPageLoad: function(Id) {
        setTimeout(function() {
            var s = s_gi('thestarprod');
            s.linkTrackVars = "products,events";
            s.linkTrackEvents = "events";
            s.products = Id;
            s.events = "prodView";
            s.tl(true, 'o', 'On Page Load Click');
        }, 10);
    },

    showTab: function(currentTab, OrderDataTab) {

        var virtualDataTab = new Array(OrderDataTab.length);
        var tab = new Array(OrderDataTab.length);
        for (var i = 1; i < (OrderDataTab.length + 1); i++) {
            virtualDataTab[i] = jQuery('#dataTab' + OrderDataTab[(i - 1)]);
            tab[i] = jQuery('#' + OrderDataTab[(i - 1)]);
        }

        for (var i = 1; i < (OrderDataTab.length + 1); i++) {
            if (virtualDataTab[i]) {
                virtualDataTab[i].hide();
                tab[i]
    .removeClass("ts-active")
    .addClass("ts-after_active");
            }
        }
        jQuery('#dataTab' + currentTab).show();
        jQuery('#' + currentTab).addClass("ts-active");

    },
    /***
    * This function toggles between tabs.
    * whichTab: The tabId to show 
    **/
    showTopicTab: function(whichTab) {
        var virtualDataTab = new Array(4);
        virtualDataTab[1] = document.getElementById('dataTab1');
        virtualDataTab[2] = document.getElementById('dataTab2');
        virtualDataTab[3] = document.getElementById('dataTab3');
        virtualDataTab[4] = document.getElementById('dataTab4');

        var tab = new Array(4);
        tab[1] = document.getElementById('tab1');
        tab[2] = document.getElementById('tab2');
        tab[3] = document.getElementById('tab3');
        tab[4] = document.getElementById('tab4');

        for (var i = 1; i < virtualDataTab.length; i++) {
            if (virtualDataTab[i]) {
                virtualDataTab[i].style.display = "none";
                tab[i].className = "ts-after_active";
            }
        }
        virtualDataTab[whichTab].style.display = "block";
        tab[whichTab].className = "ts-active";

    },

    ContentInject: function(_URL, _ID, _Params) {
        var ID;
        if (!_ID) {
            ID = 'ContentInject' + Math.random() * 5000;
            document.write('<div id="' + ID + '"></div>')
        }
        else
            ID = _ID;

        $.get(_URL, _Params,
			function(data) {
			    elem = document.getElementById(ID);
			    if (elem == null)
			        return;
			    elem.innerHTML = data;
			    //$("#" + ID).html(data);
			    TD.ProjectTheStar.EvalScript(data);
			});
    },

    /***
    * This function SHOW/ HIDE DIV.
    * @objID: the id of the object
    * @targetAction: [show /hide]
    **/
    ShowHideDiv: function(objID, targetAction) {
        var obj = document.getElementById(objID);
        if (obj)
            obj.style.display = targetAction == "hide" ? "none" : "inline";
    },

    EvalScript: function(scripts) {
        try {
            if (scripts != '') {
                var script = "";
                scripts = scripts.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function() {
                    if (scripts !== null) script += arguments[1] + '\n';
                    return '';
                });
                if (script) (window.execScript) ? window.execScript(script) : window.setTimeout(script, 0);
            }
            return false;
        }
        catch (e) { alert(e); }
    },

    SerializeInputs: function(selector) {
        var $form = $("<form></form>");
        var $container = $(selector);
        $form.append($container.clone(true)).find("select").remove();
        $container.find("select").map(function() {
            var $this = $(this);
            return $("<input type=\"hidden\" value=\"" + $this.val() + "\" name=\"" + $this.attr("name") + "\" />");
        }).appendTo($form);
        return $form.serialize();
    },

    PopupLogin: function() {
        Shadowbox_iframe('/app/loginpopup', 'Please Login', 300, 250);
        return false;
    },

    PopupContactForm: function(emailAddress) {
        Shadowbox_iframe('/app/contactformpopup/' + emailAddress, '<strong>TheStar.com E-Mail Support</strong>', 900, 600);
        return false;
    },

    CalendarDropdownInit: function(dayId, monthId, yearId) {
        var $day = $("#" + dayId);
        var $month = $("#" + monthId);
        var $year = $("#" + yearId);

        function getDays(month, year) {
            return 32 - new Date(year, month - 1, 32).getDate();
        }

        $month.add($year).change(function() {
            var selectedDay = $day.val();
            var targetDay
            $day.empty();
            for (var i = 0, len = getDays($month.val(), $year.val()); i < len; i++) {
                var d = (i + 1 < 10) ? "0" + (i + 1) : (i + 1).toString();
                $day.append("<option value=\"" + d + "\">" + d + "</option>");
            }
            $day.val(selectedDay);
        });

        $year.triggerHandler("change");
    },

    DynamicFormSubmit: function(selector, actionUrl, method) {
        $form = $(selector);
        var method = (!method) ? "post" : method;
        var randomId = "td-dynForm_" + new Date().getTime + "_" + Math.random().toString().replace(".", "");
        $dymForm = $("<form method=\"" + method + "\" action=\"" + actionUrl + "\" id=\"" + randomId + "\"></form>");
        $dymForm.hide().append($form.clone(true)).appendTo("body").submit().remove();
    },

    CheckEnter: function(evt, form, urlPath) {
        if (evt)
            keyCode = evt.keyCode;
        else
            keyCode = window.event.keyCode;

        if (keyCode == 13) {
            TD.Search.SearchAssets(document.getElementById('search_form'), urlPath);
            return false
        }

        return true;
    },

    RecipesCheckEnter: function(evt, form, urlPath) {
        if (evt)
            keyCode = evt.keyCode;
        else
            keyCode = window.event.keyCode;

        if (keyCode == 13) {
            TD.Recipes.Search('txt_search');
            return false;
        }

        return true;
    },

    ClassifiedsCheckEnter: function(evt, form, urlPath) {
        if (evt) keyCode = evt.keyCode;
        else keyCode = window.event.keyCode;

        if (keyCode == 13) {
            TD.ClassifiedsSearch.Search('search_keywords', 'search_category');
            return false;
        }
        return true;
    },

    OPAAd: {
        SetupTemplate: function(opaType) {
            if (opaType == "xxlbox") {
                $("#ts-master_container").addClass("opa-" + opaType);
                $(".ts-content_left").prepend('<div id="opa-adhelper"></div>');
                $(".opa-container").attr("id", "opa-ad");
            }
            return this;
        },
        Show: function() {
            $("#opa-ad, #opa-adhelper").show();
            return this;
        },
        Hide: function() {
            $("#opa-ad, #opa-adhelper").hide();
            return this;
        }
    },

    Query2JSON: function(query) {
        var json = {};
        var arr = query.split("&");
        for (var i = 0, j = arr.length; i < j; i++) {
            var param = arr[i].split("=");
            json[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
        }
        return json;
    },

    SetUserLastVisit: function(lastVisit, currUrl) {

        /*
        * Conditions -- set cookie only if:
        *   - Referrel hostname is internal (i.e. thestar.com or localhost:9090 or QA or staging sites)
        *      AND
        *   - if the current page isn't Timeline View
        *      OR
        *   - cookie doesn't exist
        */
        if (document.referrer.indexOf(window.location.hostname) != -1 && (currUrl.toString().indexOf("timelineview", "0") == -1 || TD.ProjectTheStar.ReadCookie(TD.ProjectTheStar.lastVisitCookieName) == null)) {
            TD.ProjectTheStar.CreateCookie(TD.ProjectTheStar.lastVisitCookieName, lastVisit, 90);
        }
    },

    GetUserLastVisit: function() {
        return TD.ProjectTheStar.ReadCookie(TD.ProjectTheStar.lastVisitCookieName);
    },

    FixIFrameHeightInParent: function(idIFrame, idContent) {
        var iFrameObj = window.parent.document.getElementById(idIFrame);
        var h = 0;
        if (iFrameObj) {
            var contentObj = document.getElementById(idContent);
            if (contentObj)
                h = (contentObj.offsetHeight ? contentObj.offsetHeight + 10 : contentObj.scrollHeight + 10) + "px";
            iFrameObj.style.height = h;
        }
    },

    ValidateSubmit: function(elemID) {
        var str = $(elemID).val();
        str = jQuery.trim(str);

        if (str == "") {
            alert("Field is blank");
            return false;
        }
        else
            return true;
    },

    ShowMap: function(ShowObjID, HideObjID1, HideObjID2) {
        var showObj = document.getElementById(ShowObjID);
        var hideObj1 = document.getElementById(HideObjID1);
        var hideObj2 = document.getElementById(HideObjID2);

        if (showObj && hideObj1 && hideObj2) {
            showObj.style.display = "inline";
            hideObj1.style.display = "none";
            hideObj2.style.display = "none";
        }
    },

    TimelineViewSetup: function(show, count, url, anchorObjID, lastVisitDate, lastVisitTime) {
        if (show == "1") {
            var divLastVisit = document.getElementById("divLastVisit");
            var anchorObj = document.getElementById(anchorObjID);

            if (divLastVisit)
                divLastVisit.innerHTML = "<h1>Today <span>(" + count + " new since your <a id='aLastVisit' class='ts-last_visit' href='" + url + "'>last visit</a>)</span></h1>";

            if (anchorObj) {
                anchorObj.innerHTML = "<div class='ts-timeline_item ts-meta_item'>" +
                                      "<div class='ts-timestamp_column'>" + lastVisitTime + "</div>" +
                                      "<div class='ts-timeline_item_content'>" +
                                        "<a name='last_visit'></a>" +
                                        "<h1 class='ts-last_visit'>" +
                                            "Your last visit (" + lastVisitDate + ")" +
                                        "</h1>" +
                                      "</div>" +
                                  "</div>";
            }
        }
    }
}

/*******************************************************************
*
* Class National
*
* This class provides functions to toggle between Toronto and 
* National editions.
*
********************************************************************/

TD.National = {
    editions: ['Toronto Edition', 'National Edition'],
    cookieName: "TheStarDefaultCity",

    /***
    * This function will setup the current edition
    * toggle and apply proper attributes
    **/
    DisplayCurrentVersion: function(currURL) {
        var nationalURL = "/national/" + currURL,
            torontoURL = "/" + currURL;

        if (TD.ProjectTheStar.ReadCookie(TD.National.cookieName) === "National Edition") {
            $("#ts-edition_link").text(TD.National.editions[1]);
            $("#ts-edition_other").text(TD.National.editions[0]);
            $("#ts-edition_other").attr({ href: "javascript:TD.National.ChangeEditionOnClick(0, '" + torontoURL + "');" });
        }
        else { // default
            $("#ts-edition_link").text(TD.National.editions[0]);
            $("#ts-edition_other").text(TD.National.editions[1]);
            $("#ts-edition_other").attr({ href: "javascript:TD.National.ChangeEditionOnClick(1, '" + nationalURL + "');" });
        }
    },

    /***
    * This function will change the current edition set in the Cookie 
    * and redirect to the appropriate page
    **/
    ChangeEditionOnClick: function(index, redirectURL) {
        TD.ProjectTheStar.CreateCookie(TD.National.cookieName, TD.National.editions[index], 9000);
        document.location = redirectURL;
    },

    /***
    * This function checks the user's preferred edition.
    * If the cookie is set, default to that edition.
    **/
    CheckPreferredEdition: function(currentEdition) {
        var cookieEdition = TD.ProjectTheStar.ReadCookie(TD.National.cookieName);
        // enforce to expire cookie if value is not valid
        if ($.inArray(cookieEdition, TD.National.editions) < 0) {
            TD.ProjectTheStar.RemoveCookie(TD.National.cookieName);
        } else {
            if (cookieEdition != currentEdition) {
                var url, currentSection;
                var currentUrl = new String(document.location.href);
                currentUrl = currentUrl.split('/');

                if (currentUrl.length < 5 || currentUrl.length > 5 && currentUrl[3].toLowerCase() == "national") {
                    if (currentEdition == "National Edition")
                        currentSection = currentUrl.length >= 5 ? currentSection = currentUrl[4] : "";
                    else
                        currentSection = currentUrl.length >= 4 ? currentSection = currentUrl[3] : "";

                    switch (cookieEdition) {
                        case "Toronto Edition":
                            url = "/" + currentSection;
                            break;
                        case "National Edition":
                            url = "/national/" + currentSection;
                            break;
                    }
                    document.location = url;
                }
            }
        }
    }
}

/**
Visual News
*/
TD.VisualNews = {
	/**
	Action on date filter
	*/
	SelectDate: function(divClass) {
	    location.search = TD.ProjectTheStar.SerializeInputs(divClass);
	},
	/**
	Inital dimmer on dimmable items
	Css Structure:
	.td-dimmable
	.td-dimmer
	.td-dimmer_background
	.td-dimmer_content
	*/
	DimmableItemInit: function() {
		$(".td-dimmable").hover(
            function() {
            	$(this).find(".td-dimmer").show();
            },
            function() {
            	$(this).find(".td-dimmer").hide();
            }
        );
	}
}



/*******************************************************************
*
* Class Search
*
* Provides functions used for the Search Results
* 
*
********************************************************************/

TD.Search = {
    SearchAssets: function(form, urlPath) {
        var searchurl = "/searchresults?AssetType=article",
            sType = "genSearch",
            headline, keywords, category, byline, body, daterange, title, orderby;
        var matchTag = /<(?:.|\s)*?>/g;

        if (form.headline)
            headline = form.headline.value;

        if (form.kquery)
            keywords = form.kquery.value;
        else {
            if (form.keywords)
                keywords = escape(form.keywords.value.replace(matchTag, ''));
        }

        if (keywords == "")
            alert("Search field can not be empty.");
        else {

            if (form.category)
                category = form.category.options[form.category.selectedIndex].value;

            if (form.byline)
                byline = form.byline.value;

            if (form.body)
                body = form.body.value;

            if (form.daterange) {
                daterange = form.daterange.options[form.daterange.selectedIndex].value;
                sType = "advSearch";
            }

            TD.ProjectTheStar.CreateCookie("title", "ALL DATES", 9000);
            if (form.daterange) {
                var temp = form.daterange.selectedIndex;
                if (temp == 0) title = "ALL DATES";
                if (temp == 1) title = "TODAY";
                if (temp == 2) title = "YESTERDAY";
                if (temp == 3) title = "PAST 3 DAYS";
                if (temp == 4) title = "PAST 14 DAYS";
                TD.ProjectTheStar.CreateCookie("title", title, 9000);
            }

            if (form.orderby && form.orderby[1].checked)
                orderby = form.orderby[1].value;

            if (daterange)
                searchurl += "&dt=" + daterange;

            if (sType)
                searchurl += "&stype=" + sType;

            if (keywords)
                searchurl += "&q=" + keywords;

            searchurl += "&r=all:1";
            if (headline || category || byline || body || daterange)
                searchurl += " AND ";

            if (headline)
                searchurl += "Title:\"" + headline + "\" AND ";

            if (category)
                searchurl += "category:\"" + category + "\" AND ";

            if (byline)
                searchurl += "(SubTitle1:\"" + byline + "\" OR SubTitle2:\"" + byline + "\") AND ";

            if (body)
                searchurl += "Body:\"" + body + "\" AND ";

            if (headline || category || byline || body || daterange)
                searchurl = searchurl.substr(0, searchurl.length - 5)

            if (orderby)
                searchurl += "&OrderBy=" + orderby;

            //check if we should do a google request instead
            if (form.searchType && form.searchType[1].checked) {
                searchurl = "http://www.google.com/search?q=" + keywords;
             }
             else if (form.searchType && form.searchType[2].checked)
             {
                searchurl = "http://www.goldbook.ca/src/torstar.php/search.html?search_type=all&searchquery=" + keywords + "&location=Toronto&x=0&y=0";
             }
             else if (window.location.hostname != "www.thestar.com" || window.location.hostname != "localhost" || window.location.hostname != "thestarrelaunch.qa.td.topscms.com" || window.location.hostname != "thestarrelaunch.staging.td.topscms.com") 
             {
                urlPath = "http://www.thestar.com";
            }

             if (urlPath != "" && urlPath != undefined)
                searchurl = urlPath + searchurl;

            document.location.href = searchurl;
        }
        return false;
    },

    DoSort: function(rawQueryString, sortByValue) {
        var select = document.getElementById("sortBy");
        var sortby = select.options[select.selectedIndex].value;
        var url = rawQueryString;
        if (sortby != 'selectsortby') {
            if (url.indexOf('sortby') != -1)
                url = url.replace(sortByValue, sortby);
            else
                url += '&sortby=' + sortby;

            document.location.href = url;
        }
    }
}


TD.AdvancedSearch = {
    init: function(selector) {

    },
    search: function(selector, host) {
        var host = host || "";
        var data = TD.ProjectTheStar.Query2JSON(TD.ProjectTheStar.SerializeInputs(selector));
        // init url
        var searchurl =
            "/searchresults?AssetType=article" +
            "&dt=" + data.daterange +
            "&stype=advSearch" +
            "&q=" + data.keywords +
            "&sortby=" + data.sortby +
            "&r=" +
            ((data.category) ? "category:\"" + data.category + "\" AND " : "all:1 AND ") +
            ((data.headline) ? "Title:\"" + data.headline + "\" AND " : "") +
            ((data.byline) ? "(SubTitle1:\"" + data.byline + "\" OR SubTitle2:\"" + data.byline + "\") AND " : "") +
            ((data.body) ? "Body:\"" + data.body + "\" AND " : "");
        searchurl = searchurl.replace(/\sAND\s$/, '');
        location.href = $.stripTags(searchurl);
    }
}




/*******************************************************************
*
* Class Search
*
* Provides functions used for the Search Results
* 
*
********************************************************************/

TD.Recipes = {
	Search: function(txtID) {
	    var txtObj = document.getElementById(txtID);
	    var matchTag = /<(?:.|\s)*?>/g;
		var url = "/living/recipes/searchresults?AssetType=Article&sortby=relevance&r=assetSubtype:Recipe&r=all:1";

		if (txtObj) {
		    var searchValue = new String(txtObj.value);
		    searchValue = searchValue.replace(matchTag, "");
			if (searchValue != "" && searchValue != " " && searchValue.toLowerCase() != "enter the dish or ingredient")
				url += "&q=" + escape(searchValue);
			window.location = url
		}
		return false;
	}
}

/*******************************************************************
*
* Class ClassifiedsSearch
*
* Provides functions used for the Classifieds Search Results
* 
*
********************************************************************/

TD.ClassifiedsSearch = {
    Search: function(keywordID, categoryID) {
        var matchTag = /<(?:.|\s)*?>/g;
        var keywordObj = document.getElementById(keywordID);
        var categoryObj = document.getElementById(categoryID);
        var url = "/classifieds/searchresults?";
        
        if (keywordObj && categoryObj) {
            var keywordValue = new String(keywordObj.value);
            keywordValue = keywordValue.replace(matchTag, "");
            var categoryValue = new String(categoryObj.value);
            
            if (categoryValue == 'Pets_Livestock') {
                url = 'http://www.gadzoo.com/thestar/SearchSummary.aspx?keyword=' + keywordValue;
            } else {
                url += "r=" + escape(categoryValue);
                if (keywordValue != "") url += "&q=" + escape(keywordValue);
            }
            window.location = url;

        }
        return false;
    }
}

/*******************************************************************
*
* Class TabToggle
*
* Provides functions used to enable tabbed functionality on Article, Topic, and other pages
*
********************************************************************/
TD.TabToggle = {

    init: function(OrderDataTab) {
        var currentTab = location.hash.replace('#', '');
        if (currentTab != "" && jQuery.inArray(currentTab, OrderDataTab) != -1) {
            TD.TabToggle.showTab(currentTab.replace('#', ''), OrderDataTab);
        }
        $('.ts-tab').click(function() {
            return TD.TabToggle.showTab($(this).attr('href').replace('#', ''), OrderDataTab);
        });
    },

    showTab: function(currentTab, OrderDataTab) {
    // Hide all
        jQuery.each(OrderDataTab, function() {
        
            jQuery('#dataTab' + this)
                .hide();
            jQuery('li[id$=tab' + this + ']')
                .removeClass("ts-active")
                .addClass("ts-after_active");
        });
        // Show only the one that was toggled
        jQuery('#dataTab' + currentTab).show();
        jQuery('li[id$=tab' + currentTab + ']').addClass("ts-active");
        window.location.hash = currentTab;
        return false;
    }
}

TD.LinkButton = {
    enterKeyFix: function(id) {
        // Fix for enter key not working on non-IE browsers
        var b = document.getElementById(id);
        if (b && typeof (b.click) == 'undefined') {
            b.click = function() {
                var result = true;
                if (b.onclick) result = b.onclick();
                if (typeof (result) == 'undefined' || result) {
                    eval(b.getAttribute('href'));
                }
            }
        }
    }
}

/** Smooth scrolling function **/
/** courtesy:  Aaron Schmidt http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12 **/
if (typeof jQuery !== 'undefined') {
    jQuery.fn.extend({
        scrollTo: function(speed, easing) {
            return this.each(function() {
                var targetOffset = $(this).offset().top;
                $('html,body').animate({ scrollTop: targetOffset }, speed, easing);
            });
        }
    });

    jQuery.extend({
        stripTags: function(s) {
            return s.replace(/<\/?[^>]+>/gi, '');
        }
    });
}

/*******************************************************************
* OPENWINMEDIA FUNCTION FOR PHOTOS PAGE
********************************************************************/
function openWinMedia(url) {
    aWindow = window.open(url, 'cgiwindow', 'Toolbar=no, Location=no, Directories=no, Status=no, Menubar=no, Scrollbars=no,  Resize=yes, width=985, height=700');
}


