﻿function isPluginLoaded(name) {
	return eval("jQuery()." + name + "||$.fn." + name + "||$." + name) ? true : false;
}
function isIE() {
	//[20110309] TODO: change please
	return $.browser.msie;
}
// image reflection
jQuery(function () {
	/*
	$("a[rel^=lightbox]").each(function(){
	//$(this).find("img").addClass("featureAlbumImage");
	//$(this).find("img").reflect();
	//$(this).css("float","left");
	});
	*/
    jEquals = function (jObj1, jObj2) {
        if (jObj1 && !jObj2 || !jObj1 && jObj2 || jObj1.length != jObj2.length)
            return false;
        for (var i = 0; i < jObj1.length; ++i)
            if (jObj1[i] !== jObj2[i]) return false;
        return true;
    };


	$("a[rel^=AlbumName]").live('click', function () {
		var findAlbum = "a[rel^='lightbox[album" + this.rel.substring(9) + "']";
		var parent = $(this).parent();
		var links = {};
		while (!links.length) {
			var links = $(findAlbum, parent);
			if (links.length > 0)
				break;
			if (!parent)
				break;
			var newParent = $(parent).parent();
			if ( newParent.length ==0 || newParent[0].nodeName.toLowerCase()=="body" || jEquals( newParent, parent) )
				break;
			parent = newParent;
		};
		if (links.length > 0) {
			//var links=$("a[rel^='lightbox']");
			for (i = 0; i < links.length; i++) {
				var a = links[i];
				links[i] = [a.href, a.title];
			}
			$.slimbox(links, 0, {});
		}
		return false;
	});
});

//hierarchy navigator switch between modes
jQuery(function () {
	var aH = $("div.sectionnavigation div.link_hierarchical a");
	//var aR = $("div.sectionnavigation div.link_related a");
	var dH = $("div.sectionnavigation div.hierarchical");
	var dR = $("div.sectionnavigation div.related");

	var aClick = function () {
		if (aH.hasClass("selected")) {
			dH.fadeOut(function () {
				aH.removeClass("selected");
				aH.text("show");
				//aR.addClass("selected");
				dR.fadeIn();
			});
		} else {
			dR.fadeOut(function () {
				//aR.removeClass("selected");
				aH.addClass("selected");
				aH.text("hide");
				dH.fadeIn();
			});
		}
	}
	if (aH)
		aH.click(aClick);
	//aR.click(aClick);
});


//limit breadcrumbs when they are longer than the allowed width of the page
jQuery(function () {
	$("ul.breadcrumb").limitBreadcrumbs();
});


/* Login fadein */
/* Change Login Image */
jQuery(function () {
	var SHOW = 1;
	var HIDE = 2;
	$('.login-li').each(function () {
		var root = $(this);
		var loginFrame = $('#loginPopUp', root);
		var loginLink = $('a.login', root);
		var autoHide = true;
		var ckRememberMe = $('.ckRememberMe', root);
		var aRememberMe = $('.aRememberMe', root);
		var butCancel = $('.login-frm-cnl', root);
		var inputs = $('.login-fld', root);
		var errorField = $('span.loginError', loginFrame);
		/*$(document).ready(function(){
		inputs.click(function(){
		inputs.val('');
		});
		});*/
		function hoverLoginLink(action) {
			var clsLoginLinkHover = 'loginhvr';
			if (action == SHOW)
				loginLink.addClass(clsLoginLinkHover);
			else
				loginLink.removeClass(clsLoginLinkHover);
		}
		function toggleLogin(action) {
			if (loginFrame.is(':visible')) {
				if (!action || action == HIDE) {
					if (isIE()) loginFrame.hide();
					loginFrame.fadeOut(function () { hoverLoginLink(HIDE) });
					inputs.bind('focus', function (event) {
						field = $(this);
						field.val('').change(function () {
							field.unbind(event);
						});
					})
				}
			} else {
				if (!action || action == SHOW) {
					if (isIE()) loginFrame.show();
					hoverLoginLink(SHOW);
					loginFrame.fadeIn('slow');
				}
			}
		}
		var timer = false;
		root.mouseenter(function () {
			if (timer) { clearTimeout(timer); timer = false; }
			toggleLogin(SHOW);
		})
		root.mouseleave(function () {
			if (!autoHide)
				return;
			if (timer) clearTimeout(timer);
			timer = window.setTimeout(function () {
				loginFrame.fadeOut('slow', function () {
					hoverLoginLink(HIDE);
				});
			}, 2000);
		});
		butCancel.click(function () {
			autoHide = true;
			toggleLogin(HIDE);
			return false;
			inputs.bind('focus', function (event) {
				$(this).val('');
			})
		});
		inputs.focus(function(){
		    autoHide = false;
		});
		loginLink.click(function () {
			autoHide = false;
			toggleLogin(SHOW);
			return false;
		});
		function rememberMe(shouldI) {
			if (shouldI) {
				//save the user and password in cookie
				setCookieAlways("rememberMe", "1");
			} else {
				setCookieAlways("rememberMe", "0");
				delCookie("rememberMe");
				delCookie("pass");
				delCookie("user");
			}
		}
		ckRememberMe.click(function () {
			rememberMe(this.checked);
			//return false;
		});
		aRememberMe.click(function () {
			var oldVal = ckRememberMe.attr("checked");
			var newVal = !oldVal;
			ckRememberMe.attr("checked", newVal)
			rememberMe(newVal);
			return false;
		});
		if (errorField.length) {
			loginFrame.show();
			hoverLoginLink(SHOW);
		}
	});
})



//add functionality for blog form: choose between adding a comment, a file or a link
jQuery(function () {
	$("div.BlogForm div.Content").each(function () {
		var root = $(this);
		var typeLink = root.find("div.PostType ul.PostTypeList li.TypeLink");
		var typeFile = root.find("div.PostType ul.PostTypeList li.TypeFile");
		var fieldFile = root.find("div.fieldFile");
		var fieldLink = root.find("div.fieldLink");
		typeLink.click(function () {
			typeLink.addClass("PostTypeSelected");
			typeFile.removeClass("PostTypeSelected");
			fieldFile.hide();
			fieldLink.show();
		});
		typeFile.click(function () {
			typeLink.removeClass("PostTypeSelected");
			typeFile.addClass("PostTypeSelected");
			fieldFile.show();
			fieldLink.hide();
		});
	});
});

jQuery(function () {
	$("div.BlogForm").each(function () {
		var root = $(this);
		var edited = false;
		var comTitleDisplay = root.find("div.comment-title-display");
		var comTitleName = root.find("span.comment-title-name");
		var comTitleEdit = root.find("div.comment-title-edit");
		var comTitleTextBox = comTitleEdit.find("input[type='text'][id$='txtCommentTitle']");
		var comTextBox = root.find("textarea[id$='txtComment']");
		comTitleDisplay.click(function () {
			comTitleDisplay.hide();
			comTitleEdit.show();
			comTitleTextBox.select();
		});
		comTitleEdit.focusout(function () {
			comTitleEdit.hide();
			comTitleName.html(comTitleTextBox.val());
			comTitleDisplay.show();
		});
		/*
		comTextBox.keyup(function(){
		var title=comTextBox.val();
		if(edited || title.length>30)
		return;
		comTitleName.html(title);
		comTitleTextBox.val(title);
		});
		*/
		comTitleTextBox.keyup(function () {
			edited = true;
		});
		var comSubmit = root.find("a.submit");
		var comSubmittedBy = root.find("input[type='text'][id$='txtSubmittedBy']");
		var comCaptcha = root.find("input.captchaText[type='text']");
		var comLink = root.find("input[type='text'][id$='txtLink']");
		var comFile = root.find("input[type='file'][id$='inputFile']");
		var errors = root.find("span.cerrors");
		function is(jQueryElem) { return jQueryElem && jQueryElem.size() > 0; }
		comSubmit.click(function () {
			var eText = ""; //"<h2 style=\"color:red\">Errors:</h2>";
			if (is(comSubmittedBy) && !comSubmittedBy.val()) {
				eText += "Please provide a name<br>";
			}
			if (!comTextBox.val() && (!is(comLink) || !comLink.val() || comLink.val() == "http://") && !is(comFile)) {
				eText += "Please provide a comment<br>";
			}
			if (is(comCaptcha) && !comCaptcha.val()) {
				eText += "Please enter the code shown.<br>";
			}
			if (eText) {
				eText = "<h2 style=\"color:red\">Errors:</h2>" + eText;
				errors.html(eText);
				return false;
			}
		});
	});
});

//author: mluc
//date: 2010-05-11
//enable comment on comment === simple Blog Form
//when user clicks on demo div, show the textarea, and on focus out, if nothing
//was input, show the demo div again
//date: 2010-05-12
//also add comment link functionality to jump to simple comment box
jQuery(function () {

	/*
	function isScrolledIntoView(elem)
	{
	var docViewTop = $(window).scrollTop();
	var docViewBottom = docViewTop + $(window).height();

	var elemTop = $(elem).offset().top;
	var elemBottom = elemTop + $(elem).height();

	return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
	&& (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
	}
	*/
	function scrollIntoView(elem) {
		var docViewTop = $(window).scrollTop();
		var docViewBottom = docViewTop + $(window).height();

		var elemTop = $(elem).offset().top;
		var elemBottom = elemTop + $(elem).height();

		var isVisible = ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
		&& (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
		if (!isVisible)
			$(window).scrollTop(elemBottom - $(window).height());
	}

	$("div.BlogFormSimple").each(function () {
		var root = $(this);
		var content = root.find("div.Content");
		var comInvite = content.find("div.commentInvite");
		var comBox = content.find("div.commentBox");
		var comText = comBox.find("textarea.simpleComment[id$='txtSimpleComment']");
		var hidIsPrivate = comBox.find("input[type='hidden'][id$='isPrivate']");
		var comPrivacyPublic = content.find("span.commentPrivacyPublic");
		var comPrivacyPrivate = content.find("span.commentPrivacyPrivate");
		comInvite.click(function () {
			comInvite.hide();
			comBox.show();
			comText.focus();
		});
		var outherBox = root.closest("div.blogCommentBody");
		comText.focusout(function () {
			if (comText.val().length == 0) {
				comBox.hide();
				comInvite.show();
				if (outherBox.find("ul.com2com").length == 0)
					root.hide();
			}
		});
		outherBox.find("a.simpleCommentLink").click(function () {
			hidIsPrivate.val("0");
			comPrivacyPublic.addClass("commentPrivacyOn");
			comPrivacyPrivate.removeClass("commentPrivacyOn");
			root.show();
			comInvite.hide();
			comBox.show();
			comText.focus();
			scrollIntoView(root);
			return false;
		});
		outherBox.find("a.simplePrivateCommentLink").click(function () {
			hidIsPrivate.val("1");
			comPrivacyPublic.removeClass("commentPrivacyOn");
			comPrivacyPrivate.addClass("commentPrivacyOn");
			root.show();
			comInvite.hide();
			comBox.show();
			comText.focus();
			scrollIntoView(root);
			return false;
		});
		comPrivacyPublic.click(function () {
			hidIsPrivate.val("0");
			comPrivacyPublic.addClass("commentPrivacyOn");
			comPrivacyPrivate.removeClass("commentPrivacyOn");
			root.show();
			comInvite.hide();
			comBox.show();
			comText.focus();
			scrollIntoView(root);
			return false;
		});
		comPrivacyPrivate.click(function () {
			hidIsPrivate.val("1");
			comPrivacyPublic.removeClass("commentPrivacyOn");
			comPrivacyPrivate.addClass("commentPrivacyOn");
			root.show();
			comInvite.hide();
			comBox.show();
			comText.focus();
			scrollIntoView(root);
			return false;
		});
	});
});

//add show all comments functionality
jQuery(function () {
	$("div.blogCommentBody").each(function () {
		var root = $(this);
		root.find("div.ShowAllCom2Com").click(function () {
			$(this).hide();
			root.find("ul.com2com").fadeIn();
		});
	});
});

jQuery(function () {
	//minimize login box if available
	$("div.page-login-box").each(function () {
		var root = $(this);
		if (!root.hasClass("enable-slide"))
			return;
		var startTime = 10 * 1000; //(10 seconds)
		var title = root.find("div.page-login-box-title");
		var body = root.find("div.page-login-box-body");
		var contentText = body.text();
		if (contentText.indexOf("User Name") >= 0 || contentText.indexOf("Password") >= 0)
			return; //don't do anything, the user still has to authenticate
		var isSliding = false;
		var aLink = $('<a style="cursor:pointer;font-size:10px;text-decoration:none;position:absolute;top:0px;right:10px;">hide</a>');
		title.append(aLink);
		var actionDone = false; //if user already clicked on the link, no need to automatically hide the content
		aLink.click(function () {
			actionDone = true;
			slide();
		});
		function slide(dir) {
			if (isSliding)
				return;
			if (dir == "up") {
				if (body.is(":visible")) {
					isSliding = true;
					aLink.text("show");
					body.slideUp('slow', function () {
						isSliding = false;
					});
				}
				return;
			}
			if (dir == "down") {
				if (body.is(":hidden")) {
					isSliding = true;
					aLink.text("hide");
					body.slideDown('slow', function () {
						isSliding = false;
					});
				}
				return;
			}
			//toggle as default action
			isSliding = true;
			if (body.is(":visible"))
				aLink.text("show");
			else
				aLink.text("hide");
			body.slideToggle('slow', function () {
				isSliding = false;
			});
		}
		window.setTimeout(function () {
			if (!actionDone && (body.attr("autoHide") === undefined || body.attr("autoHide") === false /* for Chrome */ || body.attr("autoHide") == "true")) slide("up");
		}, startTime);
	});
});

jQuery(function () {
	if (isPluginLoaded("jCarouselLite")) {
		$("div.album_carousel").each(function () {
			var root = $(this);
			var carousel = root.find("div.album_carousel_box");
			var visibleItems = root.attr("vitems") || (carousel.parents('div.listFlexible').length ? 4 : 2);
			var carousel_btnNext = root.find("a.album_next_photo");
			var carousel_btnPrev = root.find("a.album_prev_photo");
			carousel.jCarouselLite({
				btnNext: carousel_btnNext,
				btnPrev: carousel_btnPrev,
				circular: false,
				visible: visibleItems
			});
		});
	}
});

jQuery(function () {
	$("span.mot-content").each(function () {
		var root = $(this);
		var lD = root.find("div.description-long");
		var sD = root.find("div.description-short");
		var lnk = root.find("a.rSummary");

		lnk.click(function () {
			sD.delay(200).slideUp(400);
			lD.delay(800).slideDown(600);
		});
	});
});

//add functionality to show local navigation vs global
jQuery(function () {
	var root = $("div.hierachy-navigator");
	root.each(function () {
		var aH = root.find("div.link_hierarchical a");
		//var aR = $("div.sectionnavigation div.link_related a");
		var dH = root.find("div.hierarchical");
		var dR = root.find("div.related");

		var aClick = function () {
			if (aH.hasClass("selected")) {
				dH.fadeOut(function () {
					aH.removeClass("selected");
					aH.text("show");
					//aR.addClass("selected");
					dR.fadeIn();
				});
			} else {
				dR.fadeOut(function () {
					//aR.removeClass("selected");
					aH.addClass("selected");
					aH.text("hide");
					dH.fadeIn();
				});
			}
		}
		aH.click(aClick);
		//aR.click(aClick);
	});
});

jQuery(function () {
	$("div.tpl2Project,div.motNews").each(function () {
		var root = $(this);
		var lD = root.find("div.longDescription");
		var sD = root.find("div.shortDescription");
		var lnk = root.find("a.linkReadSummary");
		//        if (lnk.length > 0) {
		//            lnk.click(function(event) {
		//                if (lD.is(":hidden")) {
		//                    sD.hide('slow');
		//                    lD.show('slow');
		//                }
		//                else {
		//                    lD.hide('slow');
		//                    sD.show('slow');
		//                }
		//            });

		//        }
		lnk.toggle(
				function () {
					sD.delay(200).slideUp(400);
					lD.delay(800).slideDown(600);
				},
				function () {
					lD.delay(200).slideUp(600);
					sD.delay(1000).slideDown(600);
				}
			)
	});
});

//check for inline expandable/collapsible video in page and activate them
jQuery(function () {
	$("div.videoFrame").inlineVideo();
	$("div.videoPlayerEmbedFix").inlineFixVideo();
	$("div.videoPlayerPopup").inlineFixVideo();
	$("div.videoContentYoutube").inlineVideoYoutube();
	$("div.videoContentYoutubeFixed").inlineFixVideoYoutube();
	$("div.videoContentYoutubePopup").inlineFixVideoYoutube({ isPopup: true });
	//activate audio controls
	AudioPlayer.setup("/common/flash/audioplayer.swf", {});
	$("div.audio-container").each(function () {
		var root = $(this);
		var alternateContentId = root.find(".alternateContent").attr("id");
		var fileUrl = root.attr("soundFile");
		var width = root.attr("audioWidth");
		AudioPlayer.embed(alternateContentId, { soundFile: fileUrl, transparentpagebg: "yes", width: width, loader: "0094c2", animation: "no" });
	});
});

// calendar future and past buttons expand/collapse
jQuery(function () {
	$("div.list-items div.future-events,div.list-items div.past-events").each(function () {
		var root = $(this);
		var action = root.find("div.timeline a.action");
		var list = root.find("ul.items");
		action.click(function () {
			if (root.hasClass("collapsed-events")) {
				root.removeClass("collapsed-events");
				list.slideDown(500);
			} else {
				list.slideUp(500);
				root.addClass("collapsed-events");
			}
		});
	});
});

/*----------------------------------------- Colorbox calls ----------------------------------------*/
jQuery(function () {
	// project page, popup of committee members
	$("div.ccCommitteeSidebar div.popupContainer").each(function () {
		var root = $(this);
		var link = $("a.popupShowLink", root);
		var window = $("div.popupContent", root);
		if (link && window)
			link.colorbox({ width: "500px", height: "500px", inline: true, href: window });
	});
	$("div.ccProjectSidebar a.showCommitteeMembers").colorbox({ width: "500px", height: "500px", inline: true, href: "#listCommitteeMembers" });
	$("div.ccProjectSidebar a.showCommitteeOrganizations").colorbox({ width: "500px", height: "500px", inline: true, href: "#listCommitteeOrganizations" });

	//colorbox for popup videos
	$("a.popup-video-thumb,a.popup-video-link").each(function () {
		var elem = $(this);
		elem.colorbox({ inline: true, href: elem.attr('rel') });
	});
	//add post form displayed as popup
	$("div.mcForumForm").each(function () {
		var root = $(this);
		var link = $("a.addPostLink", root);
		var box = $("div.addPostBox", root);
		if (link) link.colorbox({ inline: true, href: box, open: $("span.cerrors", root).length, opacity: 0.5 });
		$("span.success", root).each(function () {
			$.colorbox({ inline: true, href: $(this), open: true, opacity: 0.5 });
		})
	});
});

// Privacy Settings Popup
jQuery(function () {
	$('fieldset div.setPrivacy').each(function () {
		var root = $(this);
		var trigger = root.find('a.setPrivacyButton');
		var target = root.find('div.popPrivacy');
		trigger.click(function () {
			$('fieldset div.setPrivacy div.popPrivacy').each(function () {
				$(this).css('display', 'none');
			});
			target.fadeIn(400);
		});

		var closeButtonTrigger = root.find('div.popPrivacy a.closePrivacyBox');
		closeButtonTrigger.click(function () {
			target.fadeOut(400);
		});

		$('fieldset div.setPrivacy td').each(function () {
			radioButtonContainer = $(this);
			var radioButtonTrigger = radioButtonContainer.find('input[type="radio"]');
			var Label = radioButtonContainer.find('label');
			var textToChange = Label.html();
			var Changed = radioButtonContainer.closest('div.setPrivacy').find('span.privacyText');
			radioButtonTrigger.change(function () {
				target.fadeOut(400);
				Changed.html(textToChange);
			});
		});
	});
});

// States dropdownlist enabling when the "United States" is selected
jQuery(function () {
	$('div.SignUpForm fieldset').each(function () {
		var root = $(this);
		var countries = root.find('select.countries');
		var states = root.find('select.states');
		countries.change(function () {
			var countryName = this.value;
			if (countryName == 'United States')
				states.removeAttr('disabled');
			else {
				states.attr('disabled', 'disabled');
			}
		});
	});
});

jQuery(function () {
	//$("span.VotesCount").colorbox({inline:true, href:"span.Voters"});
});



// Scroll for Newsletter sidebar
jQuery(function () {
	$('div.ccNewsletterSidebar div.NewsletterItemsSummary div.useful-links-content-liquid ul.newsletter_titles').jScrollPane();
});

/* Carousel Box */
jQuery(function () {
	if (isPluginLoaded("jCarouselLite")) {
		$(".Carousel-Box div.jCarouselLite").jCarouselLite({
			btnNext: ".Carousel-Box-right",
			btnPrev: ".Carousel-Box-left"
		});
	}
});

/* Article List scrolling bar */
jQuery(function () {
	$('div.container div.article-list').find('div.article-list-content').jScrollPane();
});

/* make tabs */
jQuery(function () {
	//[mluc:2011/02/04] THIS SHOULD NOT BE HERE!!!! It's not generic enough, please remove!
	$("div.article-list.event-bar").makeTabs2({
		tabs: "ul.etabs>li",
		contents: "ul.panese>li",
		onShow: function (curTab, curTabContent) {
			curTabContent.find(".article-list-content,.article-list-content-tab").jScrollPane();
		}
	});
	$("div.tabs-3").makeTabs2({
		tabs: "ul.wtabs li",
		contents: ".tabs-4-content",
		onShow: function (curTab, curTabContent) {
			var onShowDataFunc = curTabContent.data("makeTabs2_onShow");
			if (onShowDataFunc && typeof (onShowDataFunc) == "function")
				onShowDataFunc.call(curTabContent); //(curTab, curTabContent);
			else
				$(".makeScroll2", curTabContent).jScrollPane();
		}
	});

	$('div.panes div.tabs-4-content .makeScroll').jScrollPane();

	function getValidInt(value) {
		var val = parseInt(value);
		if (isNaN(val)) return 0;
		return val;
	}
	/* horizontal slider */
	$("ul.horizSlider").horizSlider({
		randomStart: false,
		onShow: function (li) {
			var qli = $(li);
			var descr = $('div.hpPersonDescr', qli);
			var top = $('div.top', qli);
			var H = qli.height();
			var H_top = getValidInt(top.height()) + getValidInt(top.css('margin-top')) + getValidInt(top.css('margin-bottom'));
			var bottom_spacing = 10;
			var bottom_btns = $('div.hpPerson_links', qli);
			var H_bottom = getValidInt(bottom_btns.height()) + getValidInt(bottom_btns.css('margin-top')) + getValidInt(bottom_btns.css('margin-bottom'));
			var h = H - H_top - H_bottom - bottom_spacing;
			descr.height(h);
			descr.jScrollPane();
		}
	});
	/* selectbox transform */
	if (isPluginLoaded("msDropDown")) {
		try {
			$('select.selectBoxTransform').msDropDown({ mainCSS: 'dd2' });
		} catch (ex) { alert(ex) }
	}
});

/* person page expand/collapse */
jQuery(function () {
	$('div.person-details_container').each(function () {
		var root = $(this);
		var trigger = root.find('div.person-details-title_text img.arrow');
		var target = root.find('div.person-details-content');
		trigger.toggle(function () {
			target.slideUp(400, function () {
				trigger.attr("src", '/common/images/person/arrow_up.png');
			});
		}, function () {
			trigger.attr("src", '/common/images/person/arrow_down.png');
			target.slideDown(400);
		});
	})
});

/* organization page expand/collapse */
jQuery(function () {
	$('div.organization-details_container').each(function () {
		var root = $(this);
		var trigger = root.find('div.organization-details-title_text img.arrow');
		var target = root.find('div.organization-details-content');
		trigger.toggle(function () {
			target.slideUp(400, function () {
				trigger.attr("src", '/common/images/person/arrow_up.png');
			});
		}, function () {
			trigger.attr("src", '/common/images/person/arrow_down.png');
			target.slideDown(400);
		});
	})
});


/* list members filters box expand/collapse */
jQuery(function () {
	$('div.listFlexible a.expand-filters').each(function () {
		var listFlexible = $(this).parents("div.listFlexible");
		var expandLink = $(this);
		var collapseLink = $('a.collapse-filters', listFlexible);
		var container = $('div.list-filterbox', listFlexible);
		var content = $('div.filterbox-content', container);
		var containerHeight = container.height();
		var contentHeight = content.height();
		var visibleHeight = $('div.visibleArea').height() + 47;
		expandLink.click(function () {
			$('.bla').slideDown(600);
			container.animate({ 'height': contentHeight });
			expandLink.css("display", "none");
			collapseLink.css("display", "block");
			setSessionCookie("directoryadvfilters", "1");
		});
		collapseLink.click(function () {
			$('.bla').slideUp(600);
			container.animate({ 'height': visibleHeight });
			expandLink.css("display", "block");
			collapseLink.css("display", "none");
			setSessionCookie("directoryadvfilters", "0");
		});
	});
});

/* PopUp control functionality */
jQuery.fn.makePopup = function (options) {
	/* check to see if there is a poll active */
	$("div.EntryPopUpContainer").each(function () {
		var isPopupVisible = false;
		var rootPoll = $("div.EntryPopUpPoll", this);
		if (rootPoll && rootPoll.length > 0) {
			var noVisits = parseInt(rootPoll.attr("visits")) - 1; //make sure that if set to appear on first page clicked, it will do so
			var currentVisit = rootPoll.attr("currentPage");
			var ActivePollObjectId = rootPoll.attr("activeId");
			var currentDate = rootPoll.attr("date");
			if (getCookieValue("PollFinallyShow") != "yes") {
				try {
					var visits = getCookieValue("PollPageVisits");
					var vArray = ((visits && visits.length > 0) ? visits.split("|") : []);
					var bNewVisit = true;
					var count = 0;
					for (i = 0; i < vArray.length; i++) {
						var oldVisit = vArray[i];
						if (oldVisit && oldVisit.length > 0) {
							count++;
							if (oldVisit == currentVisit)
								bNewVisit = false;
						}
					}
					if (bNewVisit && count < noVisits)
						if (count == 0)
							writeSessionCookie("PollPageVisits", currentVisit);
						else
							writeSessionCookie("PollPageVisits", (visits + "|" + currentVisit));

					if (count >= noVisits) {
						writeSessionCookie("PollFinallyShow", "yes");
						var cName = 'Polls';
						var cVal = getCookie(cName);
						if (cVal == null)
							cVal = "";
						var elemList = {}
						var activePollReg = new RegExp("\[" + ActivePollObjectId + "~[^\]]+\]");
						if (!activePollReg.test(cVal)) {
							//change_dropdown( false, false);
							//show poll in colorbox popup
							$.colorbox({
								opacity: 0.5,
								open: true,
								iframe: true,
								href: "/common/Popups/CmsPoll.aspx",
								width: options.pollWidth,
								height: options.pollHeight,
								onClosed: function () {
									//set the close cookie
									var cVal = getCookie(cName);
									if (!cVal) cVal = "";
									if (!activePollReg.test(cVal))
										setC(cName, cVal + '[' + ActivePollObjectId + '~' + currentDate + ']');
									//alert("old cookie"+cVal+" new cookie "+getCookie(cName));
									//change_dropdown( true, true);
								}
							});
							isPopupVisible = true; //the poll popup is now visible, so don't show the others
						}
					}
				} catch (ex) { alert(ex.message); }
			}
		}
		if (!isPopupVisible) {//if a popup wasn't yet shown, try to show the feature popup
			/* check if entry popup is active, and diplay it */
			var rootFeature = $("div.EntryPopUpFeature", this);
			if (rootFeature && rootFeature.length > 0) {
			    try {
                    var cookieVersion = getCookie("EntryPopUpFeatureVersion");
                    var serverVersion = rootFeature.attr("entrypopupfeatureversion")
			        setCookieAlways("EntryPopUpFeatureVersion", serverVersion);
					var COOKIE_NAME = "EntryPopUpFeature";
					var cookieStoreType = rootFeature.attr("cookieStoreType");
					var storedCookie = getCookie(COOKIE_NAME);
					//check value stored in cookie to see if corresponds to the one set on the server, and, if not reset it
					var t1 = 0; //indicates the type of store info on the server
					if (cookieStoreType == "session") t1 = 1;
					else if (cookieStoreType == "always") t1 = 2;
					else if (cookieStoreType > 0) t1 = -cookieStoreType;
					var t2 = 0; //indicates the type of store info on the client
					if (storedCookie == "session") t2 = 1;
					else if (storedCookie == "always") t2 = 2;
					else t2 = -storedCookie;
					//if both are defined, but are different, then reset cookie
                    //or the version of the server is greater than the one stored locally
					if (t1 != t2 && t2 != 0 && t1 != 0 || serverVersion>cookieVersion ) 
						delCookie(COOKIE_NAME);
					if (!getCookie(COOKIE_NAME)) {
						if (cookieStoreType == "session")
							setSessionCookie(COOKIE_NAME, "session");
						else if (cookieStoreType == "always")
							setCookieAlways(COOKIE_NAME, "always");
						else//format is days
							setCookieDays(COOKIE_NAME, cookieStoreType, cookieStoreType);
						//the days are stored in the cookie to know what type of store mode was chosen, and also are set as the expiration date
						
						$.colorbox({
							inline: true,
							opacity: 0.5,
							open: true,
							href: rootFeature,
							width: options.entryWidth,
							height: options.entryHeight,
							onComplete: function () {
								$("div.videoPopupBody div.scrollBody", rootFeature).jScrollPane();
							}
						});
					};
				} catch (ex) { alert(ex.message) }
			}
		}
	});
};

// Defaults for popup on Poll and Entry 
jQuery(function () {
    $("div.EntryPopUpFeature").makePopup({
        entryWidth:"555px",
        entryHeight:"565px"
    });
    $("div.EntryPopUpPoll").makePopup({
        entryWidth:"500px",
        entryHeight:"510px"
    });
});


/* IE7 bugfix select with fixed width  */
jQuery(function () {
	if (isPluginLoaded("ieSelectStyle")) {
		$('select.style-true').ieSelectStyle();
	};
});

//add click action
jQuery(function () {
	if (isPluginLoaded("maphilight")) {
		function rgb2hex(rgb) {
			if (rgb) {
				if (rgb.search("rgb") == -1) {
					return rgb;
				}
				var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
				delete (parts[0]);
				for (var i = 1; i <= 3; ++i) {
					parts[i] = parseInt(parts[i]).toString(16);
					if (parts[i].length == 1) parts[i] = '0' + parts[i];
				}
				return parts.join('');
			}
			return null;
		}

		try {
			$("div.mapWidget").each(function () {
				function isValid(jO) { return jO && jO.length > 0; }
				var root = $(this);
				var map = $(".map", root);
				//get fill, stroke colors
				var fillColor = rgb2hex($("span.fillColor", root).css("color")) || '8bbe3b';
				var strokeColor = rgb2hex($("span.strokeColor", root).css("color")) || 'ffffff';
				//alert("fillColor: " + fillColor + " initial: " + $("span.fillColor", root).css("background-color"));
				if (isValid(map))
					map.maphilight({
						fillColor: fillColor,
						strokeColor: strokeColor,
						fillOpacity: 1,
						groupBy: map.attr("mh_groupBy")
					});
				var selectRegion;
				var buttonGo = $("input.btnGo", root);
				//if (selectRegion.length == 0) return;
				if (isPluginLoaded("msDropDown")) {
					selectRegion = $("select.select-region", root); //.msDropDown({ mainCSS: 'dd2' }).data("dd");
					selectRegionDiv = $("select.select-region", root).msDropDown({ mainCSS: 'dd2' }).data("dd");
				}
				$("area[region^='area']", root).each(function () {
					var area = $(this);
					var index = area.attr("region").substr(4); //parseInt(area.attr("region").substr(4));
					area.click(function (e) {
						e.preventDefault();
						if (selectRegion)
							$("option[value='" + index + "']", selectRegion).attr("selected", "selected");
						if (selectRegionDiv)
							selectRegionDiv.set("selectedIndex", index);
						if (isValid(buttonGo))
							buttonGo.click();
					});
				});

				//highlight selected region
				var selRegion = $("p.selectregion", root).attr("selectedRegion");
				if (selRegion)
					highlightRegion(selRegion, fillColor);

				//to be called on postback after a region is selected
			});
		} catch (e) {
			alert("Error: " + e.message);
		}
	}
});
function highlightRegion(index, fillColor) {
	$("area[region='area" + index + "']").each(function () {
		var root = $(this);
		var data = root.data('maphilight') || {};
		data.alwaysOn = true;
		data.fillColor = fillColor;
		root.data('maphilight', data).trigger('alwaysOn.maphilight');
	})
}

/* actions bar  */
jQuery(function () {
	var selectedItem = $('div.actionsBar ul.actions_buttons li').find('a.makeSelection');
	var selectedItemContent = selectedItem.next('div.actions_description');
	selectedItem.addClass('selected');
	selectedItemContent.css('display', 'block');
	$('div.actionsBar ul.actions_buttons li').each(function () {
		var root = $(this);
		var trigger = root.find('>a');
		var triggerSelected = trigger.hasClass('makeSelection');
		var target = root.find('div.actions_description');
		var actionBar = root.parents('div.actionsBar')
		trigger.mouseover(function () {
			selectedItem.removeClass('selected');
			selectedItemContent.hide();
			target.show();
		}).mouseleave(function () {
			target.hide();
		});
		actionBar.mouseleave(function () {
			selectedItem.addClass('selected');
			selectedItemContent.show();
		});
	});

});

// toolips for actions bar
jQuery(function () {
	if ($.fn.qtip) {
		try {
			$('div.actionsBar ul.actions_buttons li a[title]').qtip({
				style: {
					name: 'dark',
					background: 'transparent',
					border: '0',
					color: '#fff',
					padding: '9px 0 5px 3px'
				},
				hide: {
					fixed: true // Make it fixed so it can be hovered over
				},
				width: {
					min: 205
				},
				position: {
					corner: {
						target: 'bottomMiddle',
						tooltip: 'topMiddle'
					},
					adjust: { x: 0, y: 2 }
				}
			});
		} catch (ex) { alert(ex.message) }
	}
});

jQuery(function () {
	$("input[type=file].image").each(function () {
		var root = $(this);
		root.change(function () {
			var ext = root.val().split('.').pop().toLowerCase();
			if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
				alert('Invalid extension! Only jpg/jpeg, gif and png extensions are allowed');
			}
		});
	});
});

// Glossary show/hide description
jQuery(function () {
	$('div.tplDefinition').each(function () {
		var root = $(this);
		var trigger = root.find('a.readMore');
		var target1 = root.find('div.description');
		var target2 = root.find('div.abstract');
		trigger.click(function () {
			trigger.hide();
			target1.hide();
			target2.show();
		})
	});
});

// set headerbar searchbox value
$(document).ready(function () {
	$('div.header div.searchbox > input').val('Enter search term');
});
