//==============================================================================
// Advanced Search Widget
//==============================================================================

if (!window.advSearch || !(typeof(window.advSearch) == 'object' || typeof(window.advSearch) == 'function')) {
	var advSearch = {};
}

//Advanced Search Initilization
advSearch.init = function () {
	
	var sFunc = 'advSearch.init', fFunc = arguments.callee;
	var oAS, //object Advanced Search config
		oF, //object Fields config
		oD, //object DOM config
		fOnChange; //function OnChange
	
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	
	//Prep vars
	oAS = this.cfg;
	oF = oAS.form.fields;
	oD = oAS.dom;
	fOnChange = function () { //Local function for date options field onchange event
		
		var onD = $(oF.date)[0], //object node Date field
			onDO = $(oF.dateOptions); //object node Date Options
		
		if (onD.selectedIndex == (onD.options.length - 1)) { //Last item in list is selected
			onDO.addClass('on');
		} else {
			onDO.removeClass('on');
		}
	};
	
	//Advanced Search check
	if (!$(oD.main).length) {
		$(oD.toggle).hide();
		return false;
	}
	
	//Init toggle
	$(oD.toggle).click(function () {
		$(oD.main).toggleClass('on');
		$(this).toggleClass('on');
		return false;
	});	
	
	//Init date fields
	$(oF.date).change(fOnChange);
	$(oF.dateFrom).datepicker({ 
		showOn: 'both', 
		buttonImage: oAS.cal.img, 
		buttonImageOnly: true,
		yearRange: '-15:+0',
		maxDate: 0,
		hideIfNoPrevNext: true,
		changeFirstDay: false
	}).attr('readonly', 'readonly');
	$(oF.dateTo).datepicker({ 
		showOn: 'both', 
		buttonImage: oAS.cal.img, 
		buttonImageOnly: true,
		yearRange: '-15:+0',
		maxDate: 0,
		hideIfNoPrevNext: true,
		changeFirstDay: false
	}).attr('readonly', 'readonly');
	fOnChange(); //Check if Custom option is selected & set class
	
	
	//Init author field
	$(oF.author).focus(function () {
		if (this.value == 'All') {
			this.value = '';
		}
	});
	$(oF.author).autocomplete({
		data: this.data.authors,
		scrollHeight: 220,
		scroll: false,
		matchContains: true
	});
	
	//Init adv submit button
	$(oD.submit).click(function () {
		advSearch.submit();
	});
	
	//Init umbrella submit button
	$(oD.umbrellaSubmit)[0].onclick = function () {
		advSearch.submit();
		return false;
	};
	
	//Init adv cancel button
	$(oD.cancel).click(function () {
		$(oD.main).toggleClass('on');
		$(oD.toggle).toggleClass('on');
		return false;
	});
	
};

//Advanced Search Configuration
advSearch.cfg = {
	cal: { //Calendar config
		img: '/images/shared/calendar_11x11.gif'
	},
	dom: { //important DOM Nodes
		main: '#advancedSearch',
		toggle: '#umbrella-toggle',
		cancel: '#advancedSearch-cancel',
		submit: '#advancedSearch-submit',
		umbrellaSubmit: '#advancedSearch-submit'
	},
	form: {
		baseUrl: 'http://search.businessweek.com/Search?',
		fields: {
			term: '#umbrella-textField',
			resultNum: '#resultsPerPage',
			date: '#advancedSearch-date',
			dateOptions: '#advancedSearch-customDateOptions',
			dateFrom: '#advancedSearch-fromDate',
			dateTo: '#advancedSearch-toDate',
			mediaType: '#advancedSearch-mediaType',
			channel: '#advancedSearch-channel',
			author: '#advancedSearch-author'
		}
	}
};

//Advanced Search Data Store
advSearch.data = {
	time: { //Millisecond counts
		day: 24*60*60*1000, //Number of milliseconds in a day
		hour: 60*60*1000 //Number of milliseconds in a hour
	},
	authors: ["Aileen Pincus", "Alaina Love", "Alyson Warhurst", "Anastasia Goodstein", "Andy Beal", "Ann Mettler", "Anthony D. Williams", "Arik Hesseldahl", "Auren Hoffman", "Ben Kunz", "Ben W. Heineman Jr.", "Bengt Nordstrom", "Beverly Behan", "Bill Buxton", "Bill George", "Bob Reed", "Brian Renwick", "Bruce Freed", "Bruce Weinstein", "Bruno Giussani", "Carmine Gallo", "Catherine Arnst", "Charles Bien", "Chetan Ahya", "Chris Albrecht", "Chris Farrell", "Christine Comaford-Lynch", "Christine Han", "Christopher Kieran", "Clay Burns", "Craig R. Barrett", "Cristine Cronin", "Curt Weeden", "Danilo Troncarelli", "Dave Douglas", "David Balekdjian", "David C. Michael", "David Cole", "David E. Gumpert", "David Everhart", "David H. Holtzman", "David Perry", "Dayton Ogden", "Deborah Matson", "Declan Ganley", "Dev Patnaik", "Diana Farrell", "Dianne Ledingham", "Don Tapscott", "Doug Ferguson", "Dov Seidman", "Dr. Philippe Pouletty", "Ed Wallace", "Edward E. Lawler III", "Elaine Coles", "Ellen Hoffman", "Fernando Gaspar", "G. Michael Maddock and Raphael Louis Viton", "Gene Marks", "Gene Marcial", "George Hallenbeck", "Gordon Orr", "Greg Blonder", "Hamilton Loeb", "Harold L. Sirkin", "Henry Chesbrough", "Jack and Suzy Welch", "James Hutcheson", "James Mehring", "James OToole", "James Olan Hutcheson", "James W. Hemerling", "Janet A. Ginsburg", "Jeffrey A. Sonnenfeld", "Jeffrey F. Rayport", "Jeneanne Rae", "Jesper Koll", "Jesse James Garrett", "Jim Champy", "John C. Maxwell", "John E. Kelly III", "John Hagel and John Seely Brown", "John Strand", "John Wood", "Jon Fine", "Jonathan Anderson", "Jonathan Sallet", "Jonathan Visbal", "Joseph Daniel McCool", "Joseph Luc Ngai", "Josh Chernoff", "Julie Daum", "Julie Meyer", "Karen E. Klein", "Keith McFarland", "Kerry J. Sulkowicz. M.D.", "Kevin P. Coyne", "Krisztina Holly", "Kurt Ronn", "Lara Lee", "Larry Keeley", "Lars Dalgaard", "Leo Hindery Jr.", "Lindsey Gerdes", "Liz Ryan", "Marc Gobe", "Maria Bartiromo", "Mark Arbeter", "Marshall Goldsmith", "Marty Bernstein", "Mary Kwak", "Michael Englund", "Michael Kaye", "Michael Watkins", "Michelle Nichols", "Navi Radjou", "Nicholas M. Donofrio", "Nikos Mourkogiannis", "Pat Cox", "Patrick Whitney", "Paul Bennett", "Piercarlo Gera", "Ram Charan", "Randall Rothenberg", "Rich Polt", "Rick Boucher", "Rick Wartzman", "Robert J. Thomas", "Robert Lawrence Kuhn", "Robert Parker", "Robert Thurman", "Roger L. Kay", "Roger Martin", "Ron Garonzik", "Ron Grover", "Ron Kermisch", "Sam Ford", "Sam Stovall", "Sarah Lacy", "Scott Flicker", "Scott Spreier", "Sharon Allen", "Shaun Rein", "Shawn T. Coyne", "Sheila Curran", "Shoshana Zuboff", "Sohrab Vossoughi", "Stephen Green", "Stephen H. Wildstrom", "Stephen J. Scott", "Steve McKee", "Steven Cody", "Steven Weber", "Stuart Spencer", "Subir Gokarn", "Surendra K. Kaushik", "Tarun Khanna", "The Staff of the Corporate Executive Board", "Thomas J. Neff", "Timothy Dunne_JDPower", "Tom Taulli", "Tony Wright", "Vicki Swisher", "Vivek Wadhwa", "Wendy Haig", "Wenran Jiang", "William J. Amelio", "William J. Holstein", "William Nobrega", "William W. Lewis"]
	
};

//Advanced Search Submit
advSearch.submit = function () {

	var sFunc = 'advSearch.submit', fFunc = arguments.callee;
	var oF /*object Fields config*/, onDate, onFrom, onTo, onType, onChan, onAuthor, dToday = new Date(), dFrom, dTo, sFrom, sTo, iSel, sType, sChan, sAuthor, sUrl;
	
	//Convert date object into mm/dd/yyyy string format
	function getDateString (dObj) {
		
		var nNum, sMonth, sDate;
		
		nNum = dObj.getMonth() + 1;
		sMonth = ((nNum < 10) ? '0' : '') + nNum;
		nNum = dObj.getDate();
		sDate = ((nNum < 10) ? '0' : '') + nNum;
		return sMonth + '/' + sDate + '/' + dObj.getFullYear();
	};
	
	//Prep vars
	oF = advSearch.cfg.form.fields;
	onDate = $(oF.date)[0]; //Date select field
	onFrom = $(oF.dateFrom); //Date from input field
	onTo = $(oF.dateTo); //Date to input field
	onType = $(oF.mediaType)[0]; //Type select field
	onChan = $(oF.channel)[0]; //Channel select field
	onAuthor = $(oF.author)[0]; //Author input field
	onTerm = $(oF.term)[0]; //Search term input field
	onResult = $(oF.resultNum)[0]; //Results number hidden field
	
	//Get dates
	iSel = onDate.selectedIndex; //option selected
	if (iSel) { //All not selected
		if (iSel == (onDate.options.length - 1)) { //Custom selected
			dFrom = onFrom.datepicker('getDate'); 
			dTo = onTo.datepicker('getDate');
		} else { //Other index selected
			dFrom = new Date(dToday.getTime() - (onDate.options[iSel].value * advSearch.data.time.day)); //Subtract number of selected days from today.
			dTo = dToday;
		}
		sFrom = getDateString(dFrom);
		sTo = getDateString(dTo);
	}
	
	//Get type
	iSel = onType.selectedIndex; //option selected
	if (iSel) {
		sType = onType.options[iSel].value;
	}
	
	//Get channel
	iSel = onChan.selectedIndex; //option selected
	if (iSel) {
		sChan = onChan.options[iSel].value;
	}
	
	//Get author
	sAuthor = escape(onAuthor.value);
	if (sAuthor == 'All' || !sAuthor) { //If All or blank
		sAuthor = '';
	}
	
	//Generate URL string
	sUrl = advSearch.cfg.form.baseUrl;
	sUrl += onTerm.name + '=' + ((onTerm.getAttribute('class') != null && onTerm.getAttribute('class').indexOf('active') != -1) ? escape(onTerm.value) : ''); //Search term field name and value
	sUrl += '&' + onResult.name + '=' + onResult.value; //Results number field name and value
	sUrl += (sFrom && sTo) ? ('&' + onFrom[0].name + '=' + sFrom + '&' + onTo[0].name + '=' + sTo) : ''; //Date from and To fields
	sUrl += (sType) ? ('&' + onType.name + '=' + sType) : ''; //Media type field
	sUrl += (sChan) ? ('&' + onChan.name + '=' + sChan) : ''; //Channel field
	sUrl += (sAuthor) ? ('&' + onAuthor.name + '=' + sAuthor) : ''; //Author field
	
	//alert('AdvSearch: Url=' + sUrl);
	
	//Submit data
	window.location.href = sUrl;
	
};