//** Accordion Content script: By Dynamic Drive, at http://www.dynamicdrive.com
//Version 1.7: March 24th, 09': Adds a 3rd revealtype setting "clickgo", which causes browser to navigate to URL specified inside the header after expanding its contents.
//Version 1.7.1: May 28th, 09': CAPT imported fix for issue that causes margins/paddings in accordion DIVs to be lost in IE8
var ddaccordion = {

	contentclassname: {}, //object to store corresponding contentclass name based on headerclass

	expandone: function(headerclass, selected) { //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone: function(headerclass, selected) { //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall: function(headerclass) { //PUBLIC function to expand all headers based on their shared CSS classname
		var jQueryheaders = jQuery('.' + headerclass)
		jQuery('.' + this.contentclassname[headerclass] + ':hidden').each(function() {
			jQueryheaders.eq(parseInt(jQuery(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall: function(headerclass) { //PUBLIC function to collapse all headers based on their shared CSS classname
		var jQueryheaders = jQuery('.' + headerclass)
		jQuery('.' + this.contentclassname[headerclass] + ':visible').each(function() {
			jQueryheaders.eq(parseInt(jQuery(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone: function(headerclass, selected, optstate) { //PUBLIC function to expand/ collapse a particular header
		var jQuerytargetHeader = jQuery('.' + headerclass).eq(selected)
		var jQuerysubcontent = jQuery('.' + this.contentclassname[headerclass]).eq(selected)
		if (typeof optstate == "undefined" || optstate == "expand" && jQuerysubcontent.is(":hidden") || optstate == "collapse" && jQuerysubcontent.is(":visible"))
			jQuerytargetHeader.trigger("evt_accordion")
	},

	expandit: function(jQuerytargetHeader, jQuerytargetContent, config, useractivated, directclick) {
		this.transformHeader(jQuerytargetHeader, config, "expand")
		jQuerytargetContent.slideDown(config.animatespeed, function() {
			config.onopenclose(jQuerytargetHeader.get(0), parseInt(jQuerytargetHeader.attr('headerindex')), jQuerytargetContent.css('display'), useractivated)
			if (config.postreveal == "gotourl" && directclick) { //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
				var targetLink = (jQuerytargetHeader.is("a")) ? jQuerytargetHeader.get(0) : jQuerytargetHeader.find('a:eq(0)').get(0)
				if (targetLink) //if this header is a link
					setTimeout(function() { if (location != targetLink.href) { location = targetLink.href } }, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
			}
		})
	},

	collapseit: function(jQuerytargetHeader, jQuerytargetContent, config, isuseractivated) {
		this.transformHeader(jQuerytargetHeader, config, "collapse")
		jQuerytargetContent.slideUp(config.animatespeed, function() { config.onopenclose(jQuerytargetHeader.get(0), parseInt(jQuerytargetHeader.attr('headerindex')), jQuerytargetContent.css('display'), isuseractivated) })
	},

	transformHeader: function(jQuerytargetHeader, config, state) {
		jQuerytargetHeader.addClass((state == "expand") ? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state == "expand") ? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location == 'src') { //Change header image (assuming header is an image)?
			jQuerytargetHeader = (jQuerytargetHeader.is("img")) ? jQuerytargetHeader : jQuerytargetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			jQuerytargetHeader.attr('src', (state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		//IMod Customization: March 28th, 10: CAPT changed this from "find" tree traversal to "children"
		else if (config.htmlsetting.location == "prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			jQuerytargetHeader.children('.accordprefix').html((state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location == "suffix")
			jQuerytargetHeader.children('.accordsuffix').html((state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect: function(headerclass) {
		var result = window.location.search.match(new RegExp(headerclass + "=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result != null) {
			result = result.toString().split(',');
		}
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie: function(Name) {
		var re = new RegExp(Name + "=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie: function(name, value) {
		document.cookie = name + "=" + value + "; path=/"
	},

	init: function(config) {
		//		console.log('init');
		document.write('<style type="text/css">\n')
		document.write('.' + config.contentclass + '{display: none}\n') //generate CSS to hide contents
		document.write('<\/style>')
		jQuery(document).ready(function(jQuery) {
			ddaccordion.urlparamselect(config.headerclass)
			var persistedheaders = ddaccordion.getCookie(config.headerclass)
			ddaccordion.contentclassname[config.headerclass] = config.contentclass //remember contentclass name based on headerclass
			config.cssclass = { collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
			config.revealtype = config.revealtype || "click"
			config.revealtype = config.revealtype.replace(/mouseover/i, "mouseenter")
			if (config.revealtype == "clickgo") {
				config.postreveal = "gotourl" //remember added action
				config.revealtype = "click" //overwrite revealtype to "click" keyword
			}
			if (typeof config.togglehtml == "undefined")
				config.htmlsetting = { location: "none" }
			else
				config.htmlsetting = { location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
			config.oninit = (typeof config.oninit == "undefined") ? function() { } : config.oninit //attach custom "oninit" event handler
			config.onopenclose = (typeof config.onopenclose == "undefined") ? function() { } : config.onopenclose //attach custom "onopenclose" event handler
			var lastexpanded = {} //object to hold reference to last expanded header and content (jquery objects)
			var expandedindices = ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders != null) ? persistedheaders : config.defaultexpanded)
			if (typeof expandedindices == 'string') //test for string value (exception is config.defaultexpanded, which is an array)
				expandedindices = expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
			var jQuerysubcontents = jQuery('.' + config["contentclass"])
			if (expandedindices.length == 1 && expandedindices[0] == "-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
				expandedindices = []
			if (config["collapseprev"] && expandedindices.length > 1) //only allow one content open?
				expandedindices = [expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
			if (config["onemustopen"] && expandedindices.length == 0) //if at least one content should be open at all times and none are, open 1st header
				expandedindices = [0]

			jQuery('.' + config["headerclass"]).each(function(index) { //loop through all headers
				if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && jQuery(this).html() != "") { //add a SPAN element to header depending on user setting and if header is a container tag
					jQuery('<span class="accordprefix"></span>').prependTo(this)
					jQuery('<span class="accordsuffix"></span>').appendTo(this)
				}
				jQuery(this).attr('headerindex', index + 'h') //store position of this header relative to its peers
				jQuerysubcontents.eq(index).attr('contentindex', index + 'c') //store position of this content relative to its peers
				var jQuerysubcontent = jQuerysubcontents.eq(index)
				var needle = (typeof expandedindices[0] == "number") ? index : index + '' //check for data type within expandedindices array- index should match that type
				if (jQuery.inArray(needle, expandedindices) != -1) { //check for headers that should be expanded automatically (convert index to string first)
					if (config.animatedefault == false)
						jQuerysubcontent.show()
					ddaccordion.expandit(jQuery(this), jQuerysubcontent, config, false) //Last param sets 'isuseractivated' parameter
					lastexpanded = { jQueryheader: jQuery(this), jQuerycontent: jQuerysubcontent }
				}  //end check
				else {
					jQuerysubcontent.hide()
					config.onopenclose(jQuery(this).get(0), parseInt(jQuery(this).attr('headerindex')), jQuerysubcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
					ddaccordion.transformHeader(jQuery(this), config, "collapse")
				}
			})

			jQuery('.' + config["headerclass"]).bind("evt_accordion", function(e, isdirectclick) { //assign custom event handler that expands/ contacts a header
				var jQuerysubcontent = jQuerysubcontents.eq(parseInt(jQuery(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if (jQuerysubcontent.css('display') == "none") {
					ddaccordion.expandit(jQuery(this), jQuerysubcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.jQueryheader && jQuery(this).get(0) != lastexpanded.jQueryheader.get(0)) { //collapse previous content?
						ddaccordion.collapseit(lastexpanded.jQueryheader, lastexpanded.jQuerycontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded = { jQueryheader: jQuery(this), jQuerycontent: jQuerysubcontent }
				}
				else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.jQueryheader && jQuery(this).get(0) != lastexpanded.jQueryheader.get(0)) {
					ddaccordion.collapseit(jQuery(this), jQuerysubcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
			})

			jQuery('.' + config["headerclass"]).bind(config.revealtype, function() {
				return false //cancel default click behavior
			})

			jQuery('.' + config["headerclass"]).find(".accordprefix").bind(config.revealtype, function() {
				if (config.revealtype == "mouseenter") {
					clearTimeout(config.revealdelay)
					var headerindex = parseInt(jQuery(this).parent().attr("headerindex"))
					config.revealdelay = setTimeout(function() { ddaccordion.expandone(config["headerclass"], headerindex) }, config.mouseoverdelay || 0)
				}
				else {
					jQuery(this).parent().trigger("evt_accordion", [true])
					return false //cancel default click behavior
				}
			})

			// CAPT added this to allow us to select the A text independantly of the LI
			jQuery('.' + config["headerclass"]).find('#pglbl').bind(config.revealtype, function() {
				//console.log("#pglbl")
				if (config.revealtype == "mouseenter") {
					clearTimeout(config.revealdelay)
					var headerindex = parseInt(jQuery(this).parent().attr("headerindex"))
					config.revealdelay = setTimeout(function() { ddaccordion.expandone(config["headerclass"], headerindex) }, config.mouseoverdelay || 0)
				}
				else {
					var jQuerysubcontent = jQuerysubcontents.eq(parseInt(jQuery(this).parent().attr('headerindex'))) //get subcontent that should be expanded/collapsed
					var targetLink = (jQuery(this).parent().is("a")) ? jQuery(this).parent().get(0) : jQuery(this).parent().find('a:eq(0)').get(0)

					if (targetLink) {
						if (location != targetLink.href) { //if this header is a link
							var newLink = targetLink.href;
							if (newLink.indexOf("?") == -1) {
								newLink += "?"
							} else {
								newLink += "&"
							}

							var tier = config["headerclass"];
							// bottom tier
							if (config["headerclass"].indexOf("3") != -1) {
								newLink += "&"
							}
							// middle tier
							if (config["headerclass"].indexOf("2") != -1) {
								newLink += "&"
							}
							// top tier
							newLink += config["headerclass"] + "=" + parseInt(jQuery(this).parent().attr('headerindex'));
							location = newLink
						}
					}
					return false //cancel default click behavior
				}
			})
			/*
			jQuery('.' + config["headerclass"]).find('.accordprefix').bind(config.revealtype, function() {
			if (config.revealtype == "mouseenter") {
			clearTimeout(config.revealdelay)
			var headerindex = parseInt(jQuery(this).parent().attr("headerindex"))
			config.revealdelay = setTimeout(function() { ddaccordion.expandone(config["headerclass"], headerindex) }, config.mouseoverdelay || 0)
			}
			else {
			jQuery(this).parent().trigger("evt_accordion", [true])
			return false //cancel default click behavior
			}
			})
			*/
			jQuery('.' + config["headerclass"]).bind("mouseleave", function() {
				clearTimeout(config.revealdelay)
			})

			config.oninit(jQuery('.' + config["headerclass"]).get(), expandedindices)

			jQuery(window).bind('unload', function() { //clean up and persist on page unload
				jQuery('.' + config["headerclass"]).unbind()
				var expandedindices = []
				jQuery('.' + config["contentclass"] + ":visible").each(function(index) { //get indices of expanded headers
					expandedindices.push(jQuery(this).attr('contentindex'))
				})
				if (config.persiststate == true && jQuery('.' + config["headerclass"]).length > 0) { //persist state?
					expandedindices = (expandedindices.length == 0) ? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
					ddaccordion.setCookie(config.headerclass, expandedindices)
				}
			})
		})
	}
}
