var $JQ = jQuery;
jQuery.noConflict(true);
var undefined;
//i like my console statements
if(typeof(console) === 'undefined') {
	console = new Object();
	console.log = function(){};
}

//just for local vs other envs incase something changes
var local = document.location.href.indexOf('localhost');
var dev = document.location.href.indexOf('dev.asme.org');
var qa = document.location.href.indexOf('qa.asme.org');

base_url = '';
if(local == -1) {
	base_url = '/';
} else {
	base_url = '/';
}

site_url = '';

if(dev != -1)
	site_url = 'http://dev.asme.org/';
if(qa != -1)
	site_url = 'http://qa.asme.org/';

if(site_url == '') {
	site_url = 'http://www.asme.org/';
	//site_url = 'http://dev.asme.org/';
}
	
//global object
var asmeJS = function (options) {
    var self = this;
    var YBStoryTitle = '';

    this.defaults = {};

    //defaults for sharing module and for tracking
    this.pageAuthor = 'ASME.org';
    this.pageDesc = 'From ASME.org';
    this.pageTitle = 'ASME';
    this.pageMediaType = 'Journal';
    this.imageURL = site_url + 'wwwasmeorg/media/images/';
    this.pageThumbnail = 'http://dummyimage.com/60x60';
    this.pageType = 'generic_page';
    this.primaryTopic = 'all_topics';
    //name-value pair for unica tracking
    this.trackingValues = '';

    this.settings = $JQ().extend({}, this.defaults, options);

    //let's get the date, just because
    this.dateToday = new Date();

    function _init() {
        console.log("starting ASME JS...");
        //checking to see if we are in the cms, in that case, let's not run the JS NOTE: removed so pages funciton inside CMS for now
        var cms = document.location.href.indexOf('/cms/');
        if (0) {
            console.log("inside kentico, stopping ASME JS...");
            return false;
        } else {
            //going to be using this partiluar div a lot, so let's store it somewhere
            self.mainContentDiv = $JQ('#main-content');
            self.headerDiv = $JQ('#asme-header');
            self.footerDiv = $JQ('#asme-footer');
            self.thomasSearch = $JQ('#thomas-search');
            self.newsSignUpModule = $JQ('#newsletter-signup-module');
            self.yellowBrix = $JQ('#yellow-brix');
            self.searchResults = $JQ('#search-results');
            self.yellowbrixHeadlines = $JQ('#yellow-brix-headlines');
            self.yellowbrixStories = $JQ('#yellow-brix-stories');

            _ieCorrections();

            self.startPage();
        }

        //misc things to do, like set logo link and search box clearing after focus
        var logoBox = self.headerDiv.find('.logo-box .logo-header');
        logoBox.bind('click', function (e) {
            e.stopPropagation();
            document.location.href = base_url;
        });

        //these functions fire depending on modules present on the page, thomasnet serach, news sign up, and search results
        self.thomasNet();
        self.newsSignUp();
        //    self.yellowbrixStoryPageTitle();

        //set up search in main header
        self.searchBox = self.headerDiv.find('.search-box');
        var $inputBox = self.searchBox.find('input');
        $inputBox.bind('focus', function () {
            var $this = $JQ(this);
            var value = $this.val();
            if (value == 'Search')
                $this.val('');
        });

        $inputBox.bind('keypress', function (e) {
            if (e.which == '13') {
                console.log("go to search page...");
                e.preventDefault();
                var $this = $JQ(this);
                var searchText = $this.val();
                searchText = encodeURIComponent(searchText);
                self.searchText = searchText;
                $JQ(document).trigger('ASMESEARCH');
            }
        });

        var $button = self.headerDiv.find('input.button');
        $button.bind('click', function (e) {
            e.preventDefault();
            var value = $inputBox.val();
            self.searchText = encodeURIComponent(value);
            $JQ(document).trigger('ASMESEARCH');

        });

        $JQ(document).bind('ASMESEARCH', function () {
            ntptAddPair('search_term', self.searchText);
            ntptEventTag('ev=internal_search');

            if (self.searchText == '')
                return false;

            var searchURL = '/search.aspx?searchText=' + self.searchText + '&';

            document.location = searchURL;

        });
        // added to display popup error message when user clicks Item in Your Cart from the 
        // global header
        // check to see if an communication error has occured
        var error = $JQ('.general-error').attr('error');
        if (error) {
            self.errorOverlay();
        }

    };

    //overlay for errors
    this.errorOverlay = function () {
        self.overlay = $JQ.ASME.newOverlay();
        var keepURL = window.document.location;
        var errorMessage = ErrorMsg;

        var html = ['<div class="cart-overlay error">',
			  '<p>' + errorMessage + '</p>',
			  '<div class="clear"></div>',
			  '<div class="float-left buttons">',
				  '<div class="blue-button"><a href="javascript:void(0)">OK</a></div>',
			  '</div>',
		  '</div>'
	];

        html = html.join('');

        self.overlay.setContent(html);
        self.overlay.show();

        $JQ('#close-overlay').bind('click', function () {
            $JQ.ASME.overlay.hide();
        });
    }

    //ie only actions
    function _ieCorrections() {
        //ie6 only actions for flyout menus
        if ($JQ.browser.msie) {
            if (parseInt($JQ.browser.version) < 7) {
                var $suckers = $JQ('.sucker-me');
                $suckers.bind('mouseover', function () {
                    var $this = $JQ(this);
                    $this.addClass('hovered');
                    $this.find('.show-me').css('left', -1);
                    $this.find('.show-me').css('top', -11);
                });

                $suckers.bind('mouseout', function () {
                    var $this = $JQ(this);
                    $this.removeClass('hovered');
                    $this.find('.show-me').css('left', -99999);
                });

            }
            //for ie only css
            if (parseInt($JQ.browser.version) < 8) {
                $JQ('body').addClass('ie7');

                var $fixMeArrows = $JQ.ASME.mainContentDiv.find('a.iefix');

                $fixMeArrows.each(function () {
                    var $this = $JQ(this);

                    $this.append('&nbsp;<img src="/wwwasmeorg/media/images/icon-arrow.png" />');

                });

                var $fixMeExitLinks = $JQ.ASME.mainContentDiv.find('.external-link');
                $fixMeExitLinks.each(function () {
                    var $this = $JQ(this);
                    $this.css('background', 'none');
                    $this.append('&nbsp;<img src="/wwwasmeorg/media/images/icon-link-external.png" />');

                });
            }
        }
    }

    //returns url for thomasnet search
    function _getThomasNetURL(which) {
        //which determines what type of thing is searched for, ie brand, product, etc
        var url = '';

        switch (which) {
            case 'prod':
                url = 'http://asme.thomasnet.com/prodsearch.html?cov=NA&which=' + which;
                break;
            case 'comp':
                url = 'http://asme.thomasnet.com/compsearch.html?cov=NA&which=' + which;
                break;
            case 'brand':
                url = 'http://asme.thomasnet.com/brandsearch.html?cov=NA&which=' + which;
                break;
        }

        return url;
    }

    //thomasNet function
    this.thomasNet = function () {
        //see if thomas net search module exists, if it does, wire it up
        if (self.thomasSearch.length) {
            //it's a button element in some cases and a div as a button sometimes
            var button = self.thomasSearch.find('#search-button');
            var buttonDiv = self.thomasSearch.find('.blue-button');
            var input = self.thomasSearch.find('input');
            var thomasNetURL = '';
            //we have to redirect the user to an outside search service, thomasnet, by appending user search terms 
            button.bind('click', function (e) {
                e.preventDefault();
                var which = self.thomasSearch.find('input:checked').val();
                thomasNetURL = _getThomasNetURL(which);
                var searchValue = input.val();
                searchValue = encodeURI(searchValue);
                thomasNetURL = thomasNetURL + '&what=' + searchValue;
                document.location = thomasNetURL;
            });

            input.bind('keypress', function (e) {
                if (e.keyCode == '13') {
                    e.preventDefault();
                    var which = self.thomasSearch.find('input:checked').val();
                    thomasNetURL = _getThomasNetURL(which);
                    var searchValue = input.val();
                    searchValue = encodeURI(searchValue);
                    thomasNetURL = thomasNetURL + '&what=' + searchValue;
                    document.location = thomasNetURL;
                }
            });

            var $links = self.thomasSearch.find('a.search-by');
            $links.bind('click', function (e) {
                e.preventDefault();
                var which = $JQ(this).attr('hook');
                thomasNetURL = _getThomasNetURL(which);
                var searchValue = input.val();
                searchValue = encodeURI(searchValue);
                thomasNetURL = thomasNetURL + '&what=' + searchValue;
                document.location = thomasNetURL;
            });

        }
    }

    //wires up newsletter signup module
    this.newsSignUp = function () {
        if (self.newsSignUpModule.length) {
            var $button = self.newsSignUpModule.find('.blue-button');
            var $input = self.newsSignUpModule.find('.email input');
            var $listName = self.newsSignUpModule.find('input:hidden');
            var $title = self.newsSignUpModule.find('#SignUpTitle');
            var $additionalinfo = self.newsSignUpModule.find('#AdditionalInfo');

            var messages = {
                successHTML: '<p class="regular"><strong>Thank you for subscribing!</strong></p><p class="regular">Please check your email to confirm and complete your subscription.</p>'
                , errorHTML: '<p class="regular"><strong>Newsletter signup is temporarily unavailable.</strong></p><p class="regular">We were unable to add your email to the list. We\'re working to fix the problem, <br /> please try again later.</p>'
                , emailError: 'Please check that you\'ve typed your email address correctly.'
                , duplicateError: 'This email address is already subscribed to this newsletter.'
            };

            function displayTooltip(message) {
                $input.parent().addClass('error');

                var $div = document.createElement('div');
                $div = $JQ($div);

                var html = [
				'<div class="content">',
					message,
				'<div class="arrow"></div></div>'
			];

                html = html.join('');

                $div.addClass('tooltip email');
                //$div.css('width', self.settings.tooltipWidth);
                $div.html(html);
                self.newsSignUpModule.append($div);

                var offset = $input.offset();
                var left = offset.left;
                var top = offset.top - 65;

                $div.css({ 'left': left, 'top': top });

                self.newsSignUpModule.tooltip = $div;
            }

            function subscribe(listName, email, callbackFunction, errorFunction) {
                $JQ.ajax({
                    url: '/ASME/Handlers/Newsletter.ashx?listName=' + listName + "&email=" + email,
                    cache: false,
                    dataType: 'json',
                    success: callbackFunction,
                    error: errorFunction,
                    timeout: 90000
                });
            }

            function subscribeSuccess(data, status) {
                $input.removeClass('loading');

                if (data != undefined || data != null) {
                    if (data.Success) {
                        $input.parent().removeClass('error');
                        $button.remove();
                        $additionalinfo.css('visibility', 'hidden');
                        self.newsSignUpModule.find('.input-text').remove();
                        $title.after(messages.successHTML);
                        $title.css('display', 'none');

                        //tracking for unica
                        var $newsletterTitle = $JQ.ASME.mainContentDiv.find('h1').text();
                        $newsletterTitle = $JQ.ASME.string.replaceWhiteSpace($newsletterTitle.toLowerCase(), '_');
                        ntptAddPair('newsletter', $newsletterTitle);
                        ntptEventTag('ev=newsletter_signup');

                        return;
                    } else {
                        $button.attr("disabled", "false");
                        $button.removeClass('disabled');

                        switch (data.ErrorCode) {
                            case 4:
                                displayTooltip(messages.emailError);
                                return;
                                break;
                            case 5:
                                displayTooltip(messages.duplicateError);
                                return;
                                break;
                            default:
                                break;
                        }
                    }
                }

                $input.parent().removeClass('error');
                $button.remove();
                $additionalinfo.css('visibility', 'hidden');
                self.newsSignUpModule.find('.input-text').remove();
                $title.after(messages.errorHTML);
                $title.css('display', 'none');
            }

            function subscribeError(xmlRequest) {
                $input.removeClass('loading');
                $input.parent().removeClass('error');
                $button.remove();
                $additionalinfo.css('visibility', 'hidden');
                self.newsSignUpModule.find('.input-text').remove();
                $title.after(messages.errorHTML);
                $title.css('display', 'none');
            }


            $input.bind('focus', function (e) {
                var $this = $JQ(this);
                var value = $this.val();
                if (value === 'Enter Your Email Address')
                    $this.val('');

                if (self.newsSignUpModule.tooltip != undefined)
                    self.newsSignUpModule.tooltip.remove();

            });

            $button.bind('click', function (e) {
                e.preventDefault();
                if (!$button.hasClass('disabled')) {
                    var inputValue = $input.val();
                    var listNameValue = $listName.val();
                    var isEmail = $JQ.ASME.validation.isEmail(inputValue);

                    if (isEmail) {
                        $input.addClass('loading');
                        $button.addClass('disabled');
                        $button.attr("disabled", "true");
                        subscribe(listNameValue, inputValue, subscribeSuccess, subscribeError);
                    } else {
                        displayTooltip(messages.emailError);
                    }
                }
            });
        }
    }

    //    //    //assign Yellowbrix story page title
    //    this.displayYellowBrixStory = function () {
    //        if (self.yellowbrixStories) {
    //            //    YBTitle





    //        }
    //    }





    //yellowbrix feeds 
    this.yellowBrixFeeds = function () {
        if (self.yellowBrix.length) {
            var hiddenDivs = self.yellowBrix.find('.hideMe');
            var html = '';
            var li = '';

            hiddenDivs.find('td.news').each(function () {
                var $this = $JQ(this);
                $this.find('a').addClass('external-link');
                li = '<li>' + $this.find('p').html() + '</li>';
                html += li;
            });

            var topicname = $JQ.ASME.mainContentDiv.find('h1').text();
            //var $TopicGUID = self.yellowBrix.find('.hideMe h1').text();
            var $YBHeadlinePageLink = '/Yellowbrix-Headlines?start=1&mhl=7&category=Engineering&ID=asme&scategory=Engineering&Topic=' + topicname;
            // html += '<li><a href="' + $YBHeadlinePageLink + '" class="arrow-blue">More from In The News</a></li>';
            /*
           Rel: 200
           Date: 1/11/2011
           Issue: Yellowbrix
           Description: Commented out the line of code below to prevent "More From In the news" to be directed to ME Magazine. ALternate solution to implemented at future date
            */
           //   html += '<li><a href="http://www.memagazine.org/Headlines.html?start=1&mhl=7&category=Engineering&ID=asme&scategory=Engineering" class="arrow-blue">More from In The News</a></li>';
           

            var $ul = self.yellowBrix.find('ul');
            //alert('final html ' + html);
            $ul.append(html);
            console.log("$u1 " + $ul.html());
            //correction for exit links, ie only
            if (parseInt($JQ.browser.version) < 8) {

                var $fixMeExitLinks = $JQ.ASME.mainContentDiv.find('.external-link');
                $fixMeExitLinks.each(function () {
                    var $this = $JQ(this);
                    $this.css('background', 'none');
                    // $this.append('&nbsp;<img src="/wwwasmeorg/media/images/icon-link-external.png" />');

                });
            }
        }
    }

    //this function is called if a search list exists on the page that requires the results to have tooltips added to them
    this.listToolTips = function () {
        if (self.searchResults.length) {
            self.searchResults.tooltips = new tooltip();
        }
    }

    //math stuff we might use
    this.math = new Object();

    //rounds given number to given places
    this.math.roundNumber = function (num, places) {
        if (places == undefined)
            places = 0;

        var factor = Math.pow(10, places);

        var result = Math.round(num * factor) / factor;

        return result;
    }

    //string stuff we may want to do
    this.string = new Object();

    this.string.replaceCharacter = function (string, removeMe, addMe) {
        string = string.replace(removeMe, addMe);
        return string;
    }

    this.string.stripWhiteSpace = function (string) {
        string = string.replace(/^\s*|\s*$/g, '');
        return string;
    }

    this.string.replaceWhiteSpace = function (string, replaceWith) {
        string = string.replace(/\s+/g, replaceWith);
        return string;
    }

    //formats date for tracking, from a string that follows "Month Year"
    this.formatDate = function (dateString) {
        var months = [['January', '01'], ['Febuary', '02'], ['March', '03'], ['April', '04'], ['May', '05'], ['June', '06'], ['July', '07'],
					  ['August', '08'], ['September', '09'], ['October', '10'], ['November', '11'], ['December', '12']];
        var dateSplit = dateString.split(' ');
        var year = dateSplit[1];
        var month = dateSplit[0];

        var matchMonth;

        for (i = 0; i < months.length; i++) {
            matchMonth = months[i][0];
            if (matchMonth == month) {
                month = months[i][1];
                i = 100;
            }
        }

        var returnDateString = year + month;

        return returnDateString;

    }

    //strip HTML function
    this.stripHTML = function (string) {
        /* var $div = document.createElement('div');
        $div = $JQ($div);
        $div.html(string);

        return $div.text();*/

        var StrippedString = string.replace(/(<([^>]+)>)/ig, " ");

        return StrippedString;

    }

    //(<[^>]+>) finds all html tags
    this.stripTAGS = function (url) {
        var regex = new RegExp("(<[^>]+>)");
        var url = unescape(url);
        var results = regex.exec(url);
        if (results == null) {
            return url;
        }
        for (var i = 0; i <= results.length; i++) {
            url = url.replace(results[i], '');
        }
        return url;
    }

    //get url values function
    this.getUrlsVars = function () {
        var vars = [], hash;
        if (window.location.href.indexOf('?') > -1) {
            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;
    }

    //get hash values from document ;location
    this.getHashValue = function (valueName) {
        var regexS = ".*(\#|\,)" + valueName + "=([^\,]*).*";
        var regex = new RegExp(regexS);
        var results = regex.exec(this.stripTAGS(window.location.href));
        if (results == null) {
            return "";
        } else {
            return results[2];
        }
    }

    //common validation methods
    this.validation = new Object();

    this.validation.regExes = {
        numRegEx: new RegExp(/^[0-9]+[0-9]*$/),
        emailRegEx: new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/),
        phoneRegEx: new RegExp(/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/),
        zipRegEx: new RegExp(/^\d{5}$|^\d{5}-\d{4}$/),
        zipSimpleRegEx: new RegExp(/^\d{5}$/),
        zipLongRegEx: new RegExp(/^\d{5}-\d{4}$/)
    }

    this.validation.isNumber = function (string) {
        return self.validation.regExes.numRegEx.test(string);
    }

    this.validation.isEmail = function (string) {
        return self.validation.regExes.emailRegEx.test(string);
    }

    this.validation.isPhone = function (string) {
        return self.validation.regExes.phoneRegEx.test(string);
    }

    this.validation.isZip = function (string) {
        return self.validation.regExes.zipRegEx.test(string);
    }

    this.validation.isZipSimple = function (string) {
        return self.validation.regExes.zipSimpleRegEx.test(string);
    }

    this.validation.isZipLong = function (string) {
        return self.validation.regExes.zipLongRegEx.test(string);
    }

    //JSONstringify and JSON Parse functions
    this.JSONstringify = function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof (v);
                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    this.JSONparse = function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };


    //cufon functions

    this.cufon = new Object();

    this.cufon.defaultClass = function () {
        if (typeof (Cufon) === 'undefined')
            return false;

        var $cufonMe = $JQ.ASME.mainContentDiv.find('.fancy-font');

        if ($cufonMe.length)
            Cufon.replace($cufonMe);
        else
            console.log("nothing to cufon");


        $cufonMe.show();
    }

    this.cufon.headers = function () {
        if (typeof (Cufon) === 'undefined')
            return false;

        var $header = $JQ.ASME.mainContentDiv.find('h1');

        if ($header.hasClass('no-cufon'))
            return false;
        Cufon.replace($header, $header.show());
        //$header.show();
    }

    //global tracking
    this.enableTracking = function () {
        //for global header
        self.headerDiv.find('a').bind('click', function () {
            var $this = $JQ(this);
            var paramValue = 'Global Nav ' + $this.text();
            paramValue = $JQ.ASME.string.replaceWhiteSpace(paramValue.toLowerCase(), '_');
            paramValue = encodeURIComponent(paramValue);
            ntptAddPair('content_module', paramValue);
            ntptEventTag('ev=click_event');
        });

        self.footerDiv.find('a').bind('click', function () {
            var $this = $JQ(this);
            var paramValue = 'Global Footer ' + $this.text();
            paramValue = $JQ.ASME.string.replaceWhiteSpace(paramValue.toLowerCase(), '_');
            paramValue = encodeURIComponent(paramValue);
            ntptAddPair('content_module', paramValue);
            ntptEventTag('ev=click_event');
        });

        //for share module
        self.shareModule = self.mainContentDiv.find('.article-share');
        self.shareModule.emailButton = self.shareModule.find('a.addthis_button_email');
        self.shareModule.printButton = self.shareModule.find('a.addthis_button_print');

        self.shareModule.emailButton.bind('click', function () {
            ntptEventTag('ev=email_page');
        });

        self.shareModule.printButton.bind('click', function () {
            ntptEventTag('ev=print_page');
        });

        //track all links leaving ASME.org, which we assume will have "http://" in the URL
        self.trackExitLinks($JQ.ASME.mainContentDiv);

    }

    //tracks exit links inside the passed obj(mainly so we can pass it search results that might link off site)
    this.trackExitLinks = function (obj) {
        obj.find('a').bind('click', function (e) {
            var $this = $JQ(this);
            var url = $this.attr('href');
            if (url == undefined)
                return false;
            if (url.indexOf('http://') != -1) {
                url = encodeURIComponent(url);
                ntptAddPair('exit_link', url);
                ntptEventTag('ev=exit_click');
            }
        });
    }

    //overlay functions (uses overlay.js)
    this.newOverlay = function () {
        return new overlay();
    }

    //flash/media player functions
    this.newFlash = function (options) {

        var flashvars = options.flashvars;
        var params = options.params;
        var attributes = options.attributes;

        var containerID = options.containerID;
        var width = options.width;
        if (width == undefined)
            width = 460;
        var height = options.height;
        if (height == undefined)
            height = 33;

        var flashLocation = base_url + 'wwwasmeorg/media/video/' + options.file;

        var flashObject = swfobject.embedSWF(flashLocation, containerID, width, height, '9.0.115', 'false', flashvars, params, attributes);
    }

    this.newPlayer = function (options) {
        //builds flash player(JWPlayer) from options passed, setting the skin and dimensions based on whether the file passed is audio or not
        //returns the swfobject in case it needs to be used afterwards
        var flashvars = options.flashvars;
        var params = options.params;
        var attributes = options.attributes;

        var containerID = options.containerID;
        var width = options.width;
        if (width == undefined)
            width = 460;
        var height = options.height;
        if (height == undefined)
            height = 33;


        if (options.type == 'audio' || options.type == 'podcast' || (options.type == undefined)) {
            console.log("it's an mp3");
            flashvars.skin = base_url + 'FlvPlayer/podcast.zip';
            height = 33;
            width = 460;
        } else {
            height = 400;
            width = 640;
            $JQ('#' + containerID).parents('.media-player').addClass('video');
            flashvars.skin = base_url + 'FlvPlayer/video.zip';
        }

        var flashLocation = base_url + 'FlvPlayer/player.swf';

        var flashObject = swfobject.embedSWF(flashLocation, containerID, width, height, '9.0.115', 'false', flashvars, params, attributes);

        return flashObject;

    }

    //function for adding ME logo to header (not always present, rules for this seem a bit hazy)
    this.addMELogo = function () {
        //NOTE: this has been nerfed per client request, 2/11/11, but leaving commented out incase it's needed again.
        //var html = '<div id="me-logo"><p class="float-left">ME Magazine</p> <a href="http://memagazine.asme.org/"><img src="/wwwasmeorg/media/images/logo-me.gif" alt="Mechanical Engineering Magazine" border="0" /></a></div>';
        //self.headerDiv.append(html);

        return false;
    }


    //main public functions (non-utility)

    this.startPage = function () {
        //js actions for article pages
        if (self.mainContentDiv.hasClass('article')) {
            self.articleJS = new ASMEarticle();
            self.articleJS.authorCheck();
            self.articleJS.getPullQuotes();
            self.articleJS.buildToolTips();
            self.articleJS.setOverlays();
            self.articleJS.buildModuleAccordions();
        }

        //js actions for product pages pages
        if (self.mainContentDiv.hasClass('product')) {
            self.productJS = new ASMEproduct();
            self.productJS.buildModuleAccordions();
            self.productJS.buildToolTips();
            self.productJS.buildTabs();

            $JQ.ASME.pageType = 'product_details_page';

        }

        //js for landing pages, might have to change this later to be more specific
        if (self.mainContentDiv.hasClass('landing')) {

            $JQ.ASME.cufon.headers();

            if (!self.mainContentDiv.hasClass('homepage'))
                $JQ.ASME.cufon.defaultClass();

            $JQ.ASME.pageType = 'Front Page';
            $JQ.ASME.primaryTopic = $JQ.ASME.mainContentDiv.find('h1').text();
            // $JQ.ASME.primaryTopic = encodeURIComponent($JQ.ASME.primaryTopic);
            $JQ.ASME.trackingValues += ',primary_topic=' + $JQ.ASME.primaryTopic;

            if ($JQ.ASME.primaryTopic == 'Knowledgebase')
                self.addMELogo();

            if ($JQ.ASME.primaryTopic == 'Shop ASME') {

                var $input = $JQ.ASME.mainContentDiv.find('#shop-search-box input');
                var $button = $JQ.ASME.mainContentDiv.find('#shop-search-box .blue-button');

                $input.bind('keypress', function (e) {
                    if (e.which == '13') {
                        e.preventDefault();
                        ntptAddPair('search_term', encodeURIComponent($input.val()));
                        ntptEventTag('ev=internal_product_search');
                    }
                });

                $button.bind('click', function () {
                    ntptAddPair('search_term', encodeURIComponent($input.val()));
                    ntptEventTag('ev=internal_product_search');
                });

            }

            if (document.location.href.indexOf('newsletter') != -1) {
                $JQ.ASME.pageType = 'newsletter';
                $JQ.ASME.primaryTopic = $JQ.ASME.mainContentDiv.find('h1').text();
            }
        }

        // js for yellowbrix-story page
        if ((document.location.href.indexOf('yellowbrix-story') != -1) && self.mainContentDiv.hasClass('article')) {
            var ybstory = $JQ.ASME.mainContentDiv.find('h1').text();
            console.log('YBStoryTitle in yellowbrix story page ' + YBStoryTitle);
            if (YBStoryTitle.length) {
                $ybstoryheader = $JQ.ASME.mainContentDiv.find('h1');
                ybstory += ' ' + YBStoryTitle;
                console.log('new story title ' + ybstory);
                $ybstoryheader.text(ybstorytitle);
            }
            $JQ.ASME.cufon.headers();
            // $JQ.ASME.displayYellowBrixStory();
            $JQ.ASME.pageType = 'yellowbrix-story';
            $JQ.ASME.primaryTopic = $JQ.ASME.mainContentDiv.find('h1').text();
        }


        //js for topic landing pages
        if (self.mainContentDiv.hasClass('topic-landing')) {
            $JQ.ASME.cufon.headers();
            $JQ.ASME.yellowBrixFeeds();

            $JQ.ASME.pageType = 'Topic Page';
            $JQ.ASME.primaryTopic = $JQ.ASME.mainContentDiv.find('h1').text();
            //$JQ.ASME.primaryTopic = encodeURIComponent($JQ.ASME.primaryTopic);
            $JQ.ASME.trackingValues += ',primary_topic=' + $JQ.ASME.primaryTopic;


            //check to see if first module in right col has class top, if not, add it (we need this for the top border)
            var $module = $JQ.ASME.mainContentDiv.find('.right-col .module:eq(0)');
            var $meMag = $JQ.ASME.mainContentDiv.find('.right-col #me-magazine');
            if (!$meMag.length)
                $module.addClass('no-border');
            var $ybStory = $JQ.ASME.mainContentDiv.find('.right-col #yellow-brix li a');
            $ybStory.click(function () {
                var $this = $JQ(this);
                YBStoryTitle = $this.text();
              //  alert('url clicked' + YBStoryTitle);
             //   console.log("yb story1 " + YBStoryTitle);
            });


            //            var $ybStory = $JQ.ASME.mainContentDiv.find('.right-col #yellow-brix li a');
            //            console.log('$ybStory ' + $ybStory.length);
            //            $ybStory.each(function (e) {

            //                var $this = $JQ(this);
            //                    YBStoryTitle = $this.find('.right-col #yellow-brix li a').text();
            //                    console.log("YBStoryTitle is " + YBStoryTitle);
            //            });
        }

        //js actions for list pages
        if (self.searchResults.length && (!self.mainContentDiv.hasClass('search'))) {
            self.listJS = new AMSElist();
            self.listJS.buildToolTips();
            self.listJS.buildTabs();
            self.listJS.wireUpTopicBrowseModule();
            self.listJS.enableTracking();
        }

        //js actions for visimo search pages
        if (self.mainContentDiv.hasClass('search')) {
            self.searchJS = new ASMESearch();

            $JQ.ASME.pageType = 'internal_search_results';
            $JQ.ASME.primaryTopic = 'internal_search_results';
        }

        //js actions for homepage
        if (self.mainContentDiv.hasClass('homepage')) {
            $JQ.ASME.pageType = 'homepage';
            //footer is different for homepage, 'skinny footer'
            $JQ.ASME.footerDiv.find('#footer-content').hide();
            $JQ.ASME.footerDiv.addClass('home-page');

            //need to check if hero module needs to have bg color changed
            var $hero = $JQ.ASME.mainContentDiv.find('#hero-module .contrast');
            var bgcolor = $hero.attr('bgcolor');
            if (bgcolor != undefined) {
                $hero.css('background', bgcolor);
            }

            var $highlightColor = self.mainContentDiv.find('#hero-module').attr('highlightColor');
            var imagePosition = self.mainContentDiv.find('#hero-module').attr('imagePosition');

            if ($highlightColor != '') {
                var $highlightSpan = self.mainContentDiv.find('#hero-module h2 span');
                $highlightSpan.css('color', $highlightColor);
            }

            if (imagePosition == '2') {
                var right = self.mainContentDiv.find('#hero-module').attr('imageRight');
                var top = self.mainContentDiv.find('#hero-module').attr('imageTop');
                var $heroImage = self.mainContentDiv.find('#hero-module img.hero-image');
                $heroImage.css('right', right);
                $heroImage.css('marginTop', top);
            }

            var $herolink = $JQ.ASME.mainContentDiv.find('#hero-link');
            var offset = $herolink.attr('offset');
            var offsetme = $herolink.attr('offsetme');

            if (offsetme == 2) {

                var $h2 = $JQ.ASME.mainContentDiv.find('#hero-module h2');
                var height = $h2.height();

                offset = parseInt(offset);
                height = parseInt(height);

                offset += height + 30;

                $herolink.css('position', 'absolute');
                $herolink.css('zIndex', 1);
                $herolink.css('top', offset);
            }

            //need to make entire hero image "section" clickable to main story
            var $heroSection = $JQ.ASME.mainContentDiv.find('#hero-module .hp-hero');
            var href = $herolink.find('a').attr('href');
            $heroSection.bind('click', function (e) {
                document.location = href;
            });

            var $addlinks = $JQ.ASME.mainContentDiv.find('#add-links');
            offset = $addlinks.attr('offset');
            offsetme = $addlinks.attr('offsetme');

            if (offsetme == 2) {

                offset = parseInt(offset);
                $addlinks.css('margin-top', offset);
            }

            //ie only arrow corrections
            if ($JQ('body').hasClass('ie7')) {
                if ($hero.length)
                    $herolink.find('a').append('&nbsp;<img src="/wwwasmeorg/media/images/arrow-white.png" />');
                else
                    $herolink.find('a').append('&nbsp;<img src="/wwwasmeorg/media/images/icon-arrow.png" />');

                var $heroImage = self.mainContentDiv.find('#hero-module img.hero-image');
                var maxWidth = 384;
                var heroWidth = $heroImage.width();

                if (heroWidth > maxWidth) {
                    var difference = heroWidth - maxWidth;
                    //difference = difference*-1;
                    var currentRight = $heroImage.css('right');
                    currentRight = currentRight.split('px');
                    currentRight = currentRight[0];
                    currentRight = parseInt(currentRight);
                    var newRight = currentRight + difference;
                    $heroImage.css('right', newRight);
                }


            }

            //line of site actions, need to add numbers to links
            var $lineOfSight = $JQ.ASME.mainContentDiv.find('#in-the-know');
            var $olLinks = $lineOfSight.find('ol li a');
            var counter = 1;

            $olLinks.each(function () {
                var $this = $JQ(this);
                var counterString = counter + '.&nbsp;';
                $this.prepend(counterString);
                counter++;
            });

            $JQ.ASME.cufon.defaultClass();

        }

        //js actions for error page
        if (self.mainContentDiv.find('h1').text() == '404') {

            self.mainContentDiv.find('.header').remove();
            self.mainContentDiv.find('div').css('border', 'none');

            $JQ.ASME.pageType = 'error_page';
            $JQ.ASME.primaryTopic = 'error_page';

        }

        //NTPT_PGEXTRA = 'page_type=' + encodeURIComponent($JQ.ASME.pageType) + $JQ.ASME.trackingValues;
        pageViewEvent = 'pv=1,lc=' + encodeURIComponent(document.location.href);
        $JQ.ASME.pageType = self.string.replaceCharacter($JQ.ASME.pageType, ' ', '_');
        $JQ.ASME.pageType = $JQ.ASME.pageType.toLowerCase();
        $JQ.ASME.primaryTopic = self.string.replaceWhiteSpace($JQ.ASME.primaryTopic.toLowerCase(), '_');
        console.log("page type is " + $JQ.ASME.pageType);
        console.log("primary topic is " + $JQ.ASME.primaryTopic);
        ntptAddPair('page_type', encodeURIComponent($JQ.ASME.pageType));
        ntptAddPair('primary_topic', encodeURIComponent($JQ.ASME.primaryTopic));
        ntptEventTag(pageViewEvent);

        self.enableTracking();

    }

    this.init = function () {
        _init();
    }

    //private functions 

    //_init();

};

$JQ.ASME = new asmeJS();

$JQ(document).ready(function() {
	$JQ.ASME.init();
});
