/* fix layout of image with captions in IE */
$(window).load(function () {
    $('.pictureCaption').each(function (a, b) {
        var c = jQuery("img", b).width();
        if (c != null) {
            $(this).css('width', c)
        } else {
            $(this).css('margin', '0px')
        }
    })
});


$(document).ready(function () {

	/* tag external links with an icon image */
    $("a[href^='http://']:not(:has(img))").each(function (a, b) {
        if ($(b).parent("h4").length < 1 && $(b).parents(".wrapper").length < 1 && $(b).parent("div").attr("class") != "player" && $(b).attr("href").indexOf(".ilo.org") == -1) {
            $(b).attr("target", "_blank");
            $(b).attr("class", "externalLink");
            $(b).append("<span id=externalLink></span>")
        }
        

	/* for rich media furniture - clashes with calendar 
	$("area[rel^='prettyPhoto']").prettyPhoto();
	$(".gallery:first a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'light_square',slideshow:3000, autoplay_slideshow: true});
	$(".gallery:gt(0) a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'fast',slideshow:10000, hideflash: true});

	$("#custom_content a[rel^='prettyPhoto']:first").prettyPhoto({
		custom_markup: '<div id="map_canvas" style="width:260px; height:265px"></div>',
		changepicturecallback: function(){ initialize(); }
		});

	$("#custom_content a[rel^='prettyPhoto']:last").prettyPhoto({
		custom_markup: '<div id="bsap_1259344" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div><div id="bsap_1237859" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6" style="height:260px"></div><div id="bsap_1251710" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div>',
		changepicturecallback: function(){ _bsap.exec(); }
		});        
    */


    });
    
    jQuery('ol').each(function () {
        $(this).children().first().addClass('first')
    })
});

/* SLIDER */
$.fn.infiniteCarousel = function () {
	function repeat(str, num) {
		return new Array( num + 1 ).join( str );
	}
	return this.each(function () {
		var $wrapper = $('> div', this).css('overflow', 'hidden'),
			$slider = $wrapper.find('> ul'),
			$items = $slider.find('> li'),
			$single = $items.filter(':first'),
			
			singleWidth = $single.outerWidth(), 
			visible = Math.round($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
			//singleWidth = 142,
			currentPage = 1,
			pages = Math.ceil($items.length / visible);            
		// 1. Pad so that 'visible' number will always be seen, otherwise create empty items
		if (($items.length % visible) != 0) {
			$slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
			$items = $slider.find('> li');
		}
		// 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
		$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
		$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
		$items = $slider.find('> li'); // reselect
		// 3. Set the left position to the first 'real' item
		$wrapper.scrollLeft(singleWidth * visible);
		// 4. paging function
		function gotoPage(page) {
			var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;
			
			$wrapper.filter(':not(:animated)').animate({
				scrollLeft : '+=' + left
			}, 500, function () {
				if (page == 0) {
					$wrapper.scrollLeft(singleWidth * visible * pages);
					page = pages;
				} else if (page > pages) {
					$wrapper.scrollLeft(singleWidth * visible);
					// reset back to start position
					page = 1;
				} 
				currentPage = page;
			});                
			return false;
		}
		// 5. Bind to the forward and back buttons
		$('a.back').click(function () {
			return gotoPage(currentPage - 1);                
		});
		$('a.forward').click(function () {
			return gotoPage(currentPage + 1);
		});
		// create a public interface to move to a specific page
		$(this).bind('goto', function (event, page) {
			gotoPage(page);
		});
	});  
};


/* Calendar */
function produceCalendar(HttpRelativeWebRoot,theLanguage,theLink,siteId,searchCriteria) {
	if(searchCriteria==null || searchCriteria==""){
		var serviceUrl = HttpRelativeWebRoot+"idcplg?IdcService=ILO_GET_EVENTS&ssSourceSiteId="+siteId+"&fromDate="+startDate+"&toDate="+endDate+"&IsJson=1&lang="+theLanguage;
	}
	else{
		searchCriteria = searchCriteria.replace(/&gt;/g,'>');
		searchCriteria = searchCriteria.replace(/&lt;/g,'<');
		searchCriteria= encodeURIComponent (searchCriteria);
		var serviceUrl = HttpRelativeWebRoot+"idcplg?IdcService=ILO_GET_EVENTS_SQL&ssSourceSiteId="+siteId+"&SearchCriteria="+searchCriteria+"&IsJson=1&lang="+theLanguage;
	}
	
	var theHref = location.href;
	if(theHref.indexOf("date=")>0){
		var dateParam = parseISO8601(theHref.substring(theHref.indexOf("date=")+5,theHref.length));
	}
	var options = {
		onMonthChanging: function(dateIn) {
	var month = dateIn.getMonth()+1;
	var year = dateIn.getFullYear();
	var firstDay = "1";
	var lastDay = (new Date(year, month, "0")).getDate();
	var startDate = month+"/"+firstDay+"/"+year;
	var endDate = month+"/"+lastDay+"/"+year;

	var jsonurl = serviceUrl;

	var jsonObj="";
	var itemNum = 0;
	var currItem;
	$.getJSON(jsonurl,
			function(data){
				itemNum = data.ResultSets.IloEvents.rows.length;
				$.each (data.ResultSets.IloEvents.rows, function (i,m) {
					$.each (m, function (j,n) {
						currItem = m[j];
						if(j==0){
							jsonObj += '{"StartDateTime":"'+currItem+'",';
						}
						if(j==1){
							jsonObj += '"EndDateTime":"'+currItem+'"}';
						}								
					});
					if(itemNum>1 && i<itemNum){
						jsonObj+=",";
					}
				});
				if(jsonObj.endsWith(",")){
					jsonObj = jsonObj.substring(0,jsonObj.length - 1);
				}
				jsonObj = '['+jsonObj+']';
				//callSomeOtherFunction(jQuery.parseJSON(jsonObj));
				$.jMonthCalendar.ReplaceEventCollection(jQuery.parseJSON(jsonObj));
			});
			return true;
		},
		onEventLinkClick: function(event) { 
			//alert("event link click");
			return true; 
		},
		onEventBlockClick: function(event) { 
			//alert("block clicked");
			return true; 
		},
		onEventBlockOver: function(event) {
			//alert(event.Title + " - " + event.Description);
			return true;
		},
		onEventBlockOut: function(event) {
			return true;
		},
		onDayLinkClick: function(date) { 
			//alert(date.toLocaleDateString());
			return true; 
		},
		onDayCellClick: function(date) { 
			//alert(date.toLocaleDateString());
			return true; 
		},
		lang: theLanguage,
		targetUrl: theLink,
		navHeight: 25,
		labelHeight: 25,
		headerHeight: 50,
		calendarStartDate: dateParam,
		navLinks: {
			enableToday: true,
			enableNextYear: true,
			enablePrevYear: true,
			p:'&lsaquo;', 
			n:'&rsaquo;', 
			t:'Today',
			showMore: '?'
		}
	};
	if(dateParam!=null){
		var today = dateParam;
	}
	else{
		var today = new Date();
	}
	var month = today.getMonth()+1;
	var year = today.getFullYear();
	var firstDay = "1";
	var lastDay = (new Date(year, month, "0")).getDate();
	var startDate = month+"/"+firstDay+"/"+year;
	var endDate = month+"/"+lastDay+"/"+year;
	var jsonurl = serviceUrl;
	var jsonObj="";
	var itemNum = 0;
	var currItem;
	$.getJSON(jsonurl,
			function(data){
				itemNum = data.ResultSets.IloEvents.rows.length;
				$.each (data.ResultSets.IloEvents.rows, function (i,m) {
					$.each (m, function (j,n) {
						currItem = m[j];
						if(j==0){
							jsonObj += '{"StartDateTime":"'+currItem+'",';
						}
						if(j==1){
							jsonObj += '"EndDateTime":"'+currItem+'"}';
						}								
					});
					if(itemNum>1 && i<itemNum){
						jsonObj+=",";
					}
				});
				//jsonObj = '['+jsonObj+']';
				if(jsonObj.endsWith(",")){
					jsonObj = jsonObj.substring(0,jsonObj.length - 1);
				}
				jsonObj = '['+jsonObj+']';
				callSomeOtherFunction(jQuery.parseJSON(jsonObj));
			});
			
	function callSomeOtherFunction(jsonObj){
		$.jMonthCalendar.Initialize(options, jsonObj);
	}
}

/* if a string ends with a specified character */
String.prototype.endsWith = function(str){
	var lastIndex = this.lastIndexOf(str);
	return (lastIndex != -1) && (lastIndex + str.length == this.length);
}

/* Contacts - x columns per row*/
/* lightbox - feature rich: RGTPL_ITEMS_06 */
/* lightbox with highlight - feature rich: RGTPL_ITEMS_08 */
var j = 1;
(function(jQuery) {
	jQuery.fn.easyListSplitter = function(options) {	
	var defaults = {			
		colNumber: 2,
		direction: 'vertical'
	};	
	this.each(function() {
		var obj = jQuery(this);
		var settings = jQuery.extend(defaults, options);
		var totalListElements = jQuery(this).children('li').size();
		var baseColItems = Math.ceil(totalListElements / settings.colNumber);
		var listClass = jQuery(this).attr('class');
		for (i=1;i<=settings.colNumber;i++){	
			if(i==1){
				jQuery(this).addClass('listCol1').wrap('<div class="listContainer'+j+'"></div>');
			} 
			else if(jQuery(this).is('ul')){
				jQuery(this).parents('.listContainer'+j).append('<ul class="listCol'+i+'"></ul>');
			} 
			else{
				jQuery(this).parents('.listContainer'+j).append('<ol class="listCol'+i+'"></ol>');
			}
			jQuery('.listContainer'+j+' > ul,.listContainer'+j+' > ol').addClass(listClass);
		}
		var listItem = 0;
		var k = 1;
		var l = 0;	
		if(settings.direction == 'vertical'){
			jQuery(this).children('li').each(function(){
				listItem = listItem+1;
				if (listItem > baseColItems*(settings.colNumber-1) ){
					jQuery(this).parents('.listContainer'+j).find('.listCol'+settings.colNumber).append(this);
				} 
				else {
					if(listItem<=(baseColItems*k)){
						jQuery(this).parents('.listContainer'+j).find('.listCol'+k).append(this);
					} 
					else{
						jQuery(this).parents('.listContainer'+j).find('.listCol'+(k+1)).append(this);
						k = k+1;
					}
				}
			});
			jQuery('.listContainer'+j).find('ol,ul').each(function(){
				if(jQuery(this).children().size() == 0) {
				jQuery(this).remove();
				}
			});	
		} 
		else{	
			jQuery(this).children('li').each(function(){
				l = l+1;
				if(l <= settings.colNumber){
					jQuery(this).parents('.listContainer'+j).find('.listCol'+l).append(this);
				} 
				else {
					l = 1;
					jQuery(this).parents('.listContainer'+j).find('.listCol'+l).append(this);
				}				
			});
		}
		jQuery('.listContainer'+j).find('ol:last,ul:last').addClass('last');
		j = j+1;
		
	});
	};
})(jQuery);

/* Facets - script that displays/hides the additional ul lists */
	function displayhide (obj) {
		var which=obj.id;
		which=which.slice(5);
		if (document.getElementById(which).style.display!="block") { 
			document.getElementById(which).style.display = "block"; 
		}
		else { 
			document.getElementById(which).style.display = "none"; 
		}
	}
	function changeSign(obj){
		obj.innerHTML = (obj.innerHTML != '[+]') ? '[+]' : '[-]';
	}

/* Generate a random number */
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});

/* looping - Quotes box */
(function($) {
	$.fn.quovolver = function(speed, delay) {
		
		/* Sets default values */
		if (!speed) speed = 500;
		if (!delay) delay = 6000;
		
		// If "delay" is less than 4 times the "speed", it will break the effect 
		// If that's the case, make "delay" exactly 4 times "speed"
		var quaSpd = (speed*4);
		if (quaSpd > (delay)) delay = quaSpd;
		
		// Create the variables needed
		var	quote = $(this),
			firstQuo = $(this).filter(':first'),
			lastQuo = $(this).filter(':last');
		
		// Hide all the quotes, then show the first
		$(this).hide();
		$(firstQuo).show();
		
		// Set the hight of the wrapper
		$(this).parent().css({height: $(firstQuo).height()});		
		
		// Where the magic happens
		if(quote.length>1){
			setInterval(function(){
				
				// Set required hight and element in variables for animation
				if($(lastQuo).is(':visible')) {
					var nextElem = $(firstQuo);
					var wrapHeight = $(nextElem).height();
				} else {
					var nextElem = $(quote).filter(':visible').next();
					var wrapHeight = $(nextElem).height();
				}
				
				// Fadeout the quote that is currently visible
				$(quote).filter(':visible').fadeOut(speed);
				
				// Set the wrapper to the hight of the next element, then fade that element in
				setTimeout(function() {
					$(quote).parent().animate({height: wrapHeight}, speed);
				}, speed);
				
				if($(lastQuo).is(':visible')) {
					setTimeout(function() {
						$(firstQuo).fadeIn(speed*2);
					}, speed*2);
					
				} else {
					setTimeout(function() {
						$(nextElem).fadeIn(speed);
					}, speed*2);
				}
				
			}, delay);
		}
	
	};
})(jQuery);

/* parse ISO 8601 datetime */
function parseISO8601(a) {
    var b = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
        date = new Date(NaN),
        month, parts = b.exec(a);
    if (parts) {
        month = +parts[2];
        date.setFullYear(parts[1], month - 1, parts[3]);
        if (month != date.getMonth() + 1) {
            date.setTime(NaN)
        }
    }
    return date
}

/* text font resizer */
$.fn.textresizer = function( options ) {
	// Stop plugin execution if no matched elements
	if( this.size() == 0 )
		return;
	var defaultSizes = buildDefaultFontSizes( this.size() );
	// Set up main options before element iteration
	var settings = $.extend( { selector: $(this).selector, sizes: defaultSizes, selectedIndex: -1 }, $.fn.textresizer.defaults, options );
	// Ensure that the number of defined sizes is suitable
	// for number of resize buttons.
	if( this.size() > settings.sizes.length ){			
		return;	// Stop execution of the plugin
	}
	// Iterate and bind click event function to each element
	return this.each( function( i ) {
		var $this = $(this);	// Current resize button
		var currSizeValue = settings.sizes[ i ];	// Size corresponding to this resize button
		// Mark this button as active if necessary
		if( settings.selectedIndex == i )
			$(this).addClass( "textresizer-active" );
		
		// Apply the font size to target element when its 
		// corresponding resize button is clicked
		$this.bind( "click", { index: i }, function( e ) {		
			settings.selectedIndex = e.data.index;
			applyFontSize( currSizeValue, settings );
			markActive( this, settings );
		});
	});
}

// Default options of textresizer plugin
$.fn.textresizer.defaults = {
	type  : "fontSize",	/* Available options: fontSize, css, cssClass */
	target: "body"		/* The HTML element to which the new font size will be applied */
};

function applyFontSize( newSize, settings ){
	var targetElm = $( settings.target );
	switch( settings.type ){
		case "css":
			// Apply new inline CSS properties
			targetElm.css( newSize );
			break;
		case "cssClass":
			// Remove previously assigned CSS class from
			// target element. Iterating through matched
			// elements ensures the class is removed
			var cssClasses = settings.sizes;
			$.each( cssClasses, function( i, value ) {
				targetElm.each( function() {
					if( $(this).hasClass( value ) )
						$(this).removeClass( value );
				});
			});
			// Now apply the new CSS class
			targetElm.addClass( newSize );
			break;
		default:
			// Apply new font size
			targetElm.css( "font-size", newSize );
			break;
	}		
}

function markActive( sizeButton, settings ){
	// Deactivate previous button
	$(settings.selector).removeClass( "textresizer-active" );
	// Mark this button as active
	$(sizeButton).addClass( "textresizer-active" );
}

function buildDefaultFontSizes( numElms ){
	var size0 = 8;				/* Initial size, measured in pixels */
	var mySizes = new Array();
	
	for( var i = 0; i < numElms; i++ ){
		// Append elements in increments of 2 units
		var value = (size0 + (i * 2)) / 10;
		mySizes.push( value + "em" );	
	}
	return mySizes;
}


