var undefined;

var AMSElist = function (options) {

    var self = this;

    this.defaults = {
        breadcrumb: '<li><a id="all-topics" href="javascript:void(0)">All</a>&nbsp;<span>&gt;</span>&nbsp</li>'
    };

    this.settings = $JQ().extend({}, this.defaults, options);

    function _init() {
        console.log("starting ASME Lists JS...");
        self.browseModule = $JQ.ASME.mainContentDiv.find('.browse');
        self.topicList = $JQ.ASME.mainContentDiv.find('#topic-list');
        self.desList = $JQ.ASME.mainContentDiv.find('#des-list');
        self.subTopicDiv = document.createElement('ul');
        self.subTopicDiv = $JQ(self.subTopicDiv);
        self.subTopicDiv.attr('id', 'sub-topcs');
        self.subTopicDiv.css({ 'float': 'left', 'clear': 'both', 'min-width':'200px' });
        self.testList = '<ul><li><a href="javascript:void(0)">Sub Item #1</a></li><li><a href="javascript:void(0)">Sub Item #2</a></li><li><a href="javascript:void(0)">Sub Item #3</a></li></ul>';

        //creating breadcrumb from browse by topic module
        self.bcFlag = false;
        self.breadcrumb = document.createElement('ul');
        self.breadcrumb = $JQ(self.breadcrumb);
        self.breadcrumb.addClass('topic-breadcrumb');
        self.breadcrumb.hide();

        //check URL to see if breadcrumb needs to be pre-populated.
        var buildBC = document.location.href.indexOf('itemName');
        if (buildBC != -1) {
            self.buildBC();

        } else {
            self.bcFlag = false;
            self.breadcrumb.html(self.settings.breadcrumb);
        }
        

        self.subTopicDiv.wire = function () {
            var subTopics = self.subTopicDiv.find('li a');
            subTopics.bind('click', function () {
                var $this = $JQ(this);
                self.currentSubTopic = $this;
                $JQ(document).trigger('SUBTOPIC');
            });
        }
		
		self.populateSearchBox();
       
    }
	
    //fetches search term and returns it
	function _getSearchTerm() {
		var searchTerm = $JQ.ASME.getHashValue('searchBy');
		if (searchTerm == '') {
			searchTerm = $JQ.ASME.getUrlsVars();
			searchTerm = searchTerm['searchBy'];
		}	
		
		return searchTerm;
	}

    //public functions
	
	//builds breadcrumb based on URL/hash
	this.buildBC = function() {
			self.bcFlag = true;
			//var hash = location.hash;
			//console.log(hash);

			var taxGUID = $JQ.ASME.getHashValue('tax');
			self.taxGUID = taxGUID;
			var itemName = $JQ.ASME.getHashValue('itemName');
			itemName = unescape(itemName);

			var liHTML = '<li name="' + taxGUID + '">' + itemName + '</li>';
			var html = self.settings.breadcrumb + liHTML;
			self.breadcrumb.html(html);
			
			var $allCrumb = self.breadcrumb.find('#all-topics');

			self.topics = self.topicList.find('.module li');
	
			$allCrumb.bind('click', function () {
				$JQ(document).trigger('ALLTOPICS');
				//location.hash = 'tax=';
			});
			
	}
	
    this.buildTabs = function () {
        console.log("building browse tabs...");
        if (!self.browseModule)
            return false;

        var $headers = self.browseModule.find('h2');

        //we only need to wire up tab functionality if there are more than one header
        if ($headers.length > 1) {
            $headers.css('cursor', 'pointer');
            //hide tab contents beyond the initial tab
            var $tabs = $JQ.ASME.mainContentDiv.find('.tab-content');
            $JQ.ASME.mainContentDiv.find('.tab-content:gt(0)').hide();

            var hook = 0;

            $headers.each(function () {
                var $this = $JQ(this);

                //assigning a hook to the tab based on it's position, ie which tab is it, first, second, etc
                $this.attr('hook', hook);
                hook++;

                $this.bind('click', function (e) {
                    //the tab is the corrseponding tab-contnet div, stored earlier
                    var $tab = $JQ($tabs[parseInt($this.attr('hook'))]);
                    $tabs.hide();
                    $tab.show();
                    $this.addClass('on').siblings('h2').removeClass('on');
                });

            });

            if (self.bcFlag) {
                self.desList.hide();
                self.topicList.show();
                self.browseModule.find('h2:eq(0)').removeClass('on');
                self.browseModule.find('h2:eq(1)').addClass('on');
            }

        }
        else if ($headers.length == 1) {
            $headers.css('color', '#242424');
			$headers.css('fontWeight', 'bold');
            return false;
        }

    }

    //creates lists tooltips
    this.buildToolTips = function () {
        self.tooltips = new tooltip();
    }

    //wires up browse by topic functionality
    this.wireUpTopicBrowseModule = function () {
        console.log('wiring topic browse module...');

        //add breadcrumb, contents have been determined in init() because we have to check the URL first
        self.topicList.prepend(self.breadcrumb);

        var $allCrumb = self.breadcrumb.find('#all-topics');

        self.topics = self.topicList.find('.module li');

        self.topics.bind('click', function () {
            var $this = $JQ(this);
            var newCrumb = $this.text();
            var name = $this.find('a').attr('name');
            newCrumb = '<li name="' + name + '">' + newCrumb + '&nbsp</li>';
            self.topicList.children().hide();
            self.breadcrumb.append(newCrumb).show();
            //using dummy markup for now to simular children
            //self.subTopicDiv.html(self.testList);
            //self.topicList.append(self.subTopicDiv);
            //self.subTopicDiv.wire();
            self.subTopicDiv.show();
        });

        $allCrumb.bind('click', function () {
            $JQ(document).trigger('ALLTOPICS');

        });

        $JQ(document).bind('ALLTOPICS', function (e) {
            self.topicList.children().show();
            self.breadcrumb.hide();
            self.breadcrumb.find('li:gt(0)').remove();
            self.subTopicDiv.hide();
			
			var searchTerm = _getSearchTerm();
			
			if(searchTerm != undefined && searchTerm != '') 
				location.hash = 'searchBy=' + searchTerm;

        });
        $JQ(document).bind('SUBTOPIC', function (e) {
            e.stopPropagation();
            var $this = $JQ(this.activeElement);

            var $lastCrumb = self.breadcrumb.find('li:last');
            var name = $lastCrumb.attr('name');
            $lastCrumb.wrapInner('<a href="javascript:void(0)" name="' + name + '"></a>');
            $lastCrumb.bind('click', function () {
                var $this = $JQ(this);
                $this.unbind();
                var text = $this.find('a').text();
                $this.find('a').remove();
                $this.text(text);
                $this.nextAll('li').remove();
                //self.topicList.append(self.subTopicDiv);
                text = $JQ.ASME.string.stripWhiteSpace(text);
                var taxonomyGUID = $this.attr('name');
				var searchTerm = _getSearchTerm();
				
				if(searchTerm != undefined && searchTerm != '') 
					location.hash = 'itemName=' + encodeURIComponent(text).replace(/%C2%A0/g, '') + ',tax=' + taxonomyGUID + ',searchBy=' + searchTerm;
				else
                	location.hash = 'itemName=' + encodeURIComponent(text).replace(/%C2%A0/g, '') + ',tax=' + taxonomyGUID;
					
                $JQ('.error, #list-results, .pagination, #list-displaying, #sort-select, #list-displaying-in').hide();
                $JQ.ASME.mainContentDiv.find('#search-results').addClass('loading');
                //ASMEListResults.getListResultsFromID(taxonomyGUID, function(){$JQ.ASME.mainContentDiv.find('#search-results').removeClass('loading');ASMEListResults.loadResults;});
                self.subTopicDiv.show();
                //ASMEMakeFilter.getTaxonomy(function(){self.subTopicDiv.show();}, $this.attr('name'));	

            });

            var newCrumb = self.currentSubTopic.text();
            newCrumb = '<li><span>&gt;</span>&nbsp;' + newCrumb + '&nbsp</li>';
            self.topicList.children().hide();
            self.breadcrumb.append(newCrumb).show();
        });

        if (self.bcFlag) {
            self.topicList.children().hide();
            self.breadcrumb.show();
            self.subTopicDiv.show();
        }

        self.desList.find('a').bind('click', function () {
            self.topicList.children().show();
            self.breadcrumb.hide();
            self.breadcrumb.find('li:gt(0)').remove();
            self.subTopicDiv.hide();
        });

    }

    //list page specific tracking
    this.enableTracking = function () {
        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_list_search');
            }
        });

        $button.bind('click', function () {
            ntptAddPair('search_term', encodeURIComponent($input.val()));
            ntptEventTag('ev=internal_list_search');
        });
		
		$JQ.ASME.pageType = 'product_category_page';
		var productType = $JQ.ASME.mainContentDiv.find('h1').text();
		productType = productType.toLowerCase();
		if(productType != 'news & articles')
			ntptAddPair('product_type', encodeURIComponent(productType));
		
		self.desList.find('a').bind('click', function(e) {
			var $this = $JQ(this);
			var text = $this.text();
			text = $JQ.ASME.string.replaceWhiteSpace(text.toLowerCase(), '_');
			ntptAddPair('filter_name', text);
            ntptEventTag('ev=list_filter');												  
		});
		
		self.topicList.find('a').bind('click', function(e) {
			var $this = $JQ(this);
			var text = $this.text();
			text = $JQ.ASME.string.replaceWhiteSpace(text.toLowerCase(), '_');
			ntptAddPair('filter_name', text);
            ntptEventTag('ev=list_filter');												  
		});
		
    }
	
	this.populateSearchBox = function() {
		$JQ.ASME.pageTitle = $JQ.ASME.mainContentDiv.find('h1').text();
		var searchString = 'Search ' + $JQ.ASME.pageTitle;
		var $input = $JQ.ASME.mainContentDiv.find('#shop-search-box input');
		var $button = $JQ.ASME.mainContentDiv.find('#shop-search-box .blue-button');
		//needed to do this for shop landing scoped search, was replacing input value with "Search All Products",
        //wanted it to be the search term that was entered
        if (1) {
           $input.val(searchString); 
        }
		
		$input.bind('focus', function () {
            var $this = $JQ(this);
            var value = $this.val();
            if (value == searchString)
                $this.val('');
        });
		
	}

    _init();

};
  
