// JQuery wordCount plugin for textarea

var max_words = 500;
jQuery.fn.wordCount = function(params){
	var p = {
		counterElement:"display_count"
	};
	var total_words;
	
	if(params) {
		jQuery.extend(p, params);
	}
	
	//for each keypress function on text areas
	this.keyup(function()
	{ 
		total_words= this.value.split(/[\s\?]+/).length;
		$('#'+p.counterElement).html(total_words);
		if (total_words > max_words) {
			//var textarea500 = this.value.split(/[\s\.\?]+/);
			var textarea500 = this.value.split(" ");
			var testa = textarea500.slice(0,max_words-1);
			testa = testa.toString().replace(/,/g," ");
			alert("Max " + max_words + " words.");
			$(this).val(testa);
			total_words=max_words - this.value.split(/[\s\.\?]+/).length;
			$('#'+p.counterElement).html(total_words);
		}
	});	
};
// end JQuery wordCount plugin for textarea

// JS objects inc. widget code and flash text replacement to appear here
var apply = function(o, e){
    for(var p in e) o[p] = e[p];
    return o;
};

// allow browser console (Firefox and Safari) logging without breaking IE
var debug = true;
var log = ((debug && typeof console == "object") ? function (logStr) { console.log(logStr) } : function () {} );


var wrapColumns = function () {
    $("#nav-sub-list>ul").hide(0);


    var columnWrapper = function (inItemsPerColumn){
        var nextColumnLength = function () {
            var nextItemIndex = (arrayPointer >= itemsPerColumn.length ? itemsPerColumn.length -1 : arrayPointer);
            arrayPointer++;
            return itemsPerColumn[nextItemIndex];
        }
        var itemsPerColumn = [3];
        if ((typeof inItemsPerColumn == "number") || (typeof inItemsPerColumn == "integer")) {
            itemsPerColumn[0] = inItemsPerColumn;
        } else if (typeof inItemsPerColumn == "object") {
            itemsPerColumn = inItemsPerColumn;
        }
        
        var arrayPointer = 0;    
        do {
            nextChunk = $("#nav-sub-list>ul>li:not(.nav-sub-col):lt(" + nextColumnLength() +")");    
            $(nextChunk).wrapAll('<li class="nav-sub-col"><ul></ul></li>');
        } while (nextChunk.length > 0)  
    }
    var singleItemColumn = function (inString) {
        var singleItemRegex = new RegExp(/^Overview|Over BDP.Khandekar|Overzicht|Projecten|Celebrating 50 Years/i);
        return (singleItemRegex.test(inString));
    }
	   
    var colWrap = $("#nav-sub-list>ul>li");
    var colArray = [];
    var maxCols = 5;
    var defaultItemsPerColumn = 3;
    var remainingItemCount = colWrap.length;
    var remainingColumns = maxCols;
    
    if (remainingItemCount > 0) {
        if (singleItemColumn($(colWrap[0]).text())) {
            colArray.push(1);
            remainingColumns = maxCols-1;
            remainingItemCount--;
        }
        if (remainingItemCount > (remainingColumns * defaultItemsPerColumn)) {
            colArray.push(Math.floor(remainingItemCount / remainingColumns) + (remainingItemCount % remainingColumns == 0 ? 0 : 1));
        } else {
            colArray.push(defaultItemsPerColumn);
        }
    }
    columnWrapper(colArray);
    $("#nav-sub-list>ul").addClass("columnsWrapped").show(0);
}


var checkLanguageUrl = function() {
	var pageURL = window.location.pathname;
	var urlRegex = /^\/nl\//;	
	checkLanguageUrl = urlRegex.test(pageURL);
	return checkLanguageUrl;
}

var addClassesToFeaturedNewsItems = function() {
	//var ItemsCount = $("#promo3").find("li").length;
	/*
	var counter = 1;
	$("#promo3").find("li").each(function() {
		$(this).attr("class","item"+counter);
		counter++;
	});
	*/
	if (!$('body').hasClass('sub')) {

		$("#promo3").find("a").hover(
			function () {
				$(this).parent().addClass("item" + $(this).parent().prevAll().length);
				//$(this).parent().addClass("item" + $('li', $(this).parent().parent()).index(this));
			},
			function () {
				$(this).parent().removeClass("item" + $(this).parent().prevAll().length);
				//$(this).parent().removeClass("item" + $('li', $(this).parent().parent()).index(this));
			}
		);
	}
	else {
		if (checkLanguageUrl) {
			$("#promo3").find("a").hover(
				function () {
					$(this).parent().addClass("itemSub" + $(this).parent().prevAll().length);
					//$(this).parent().addClass("item" + $('li', $(this).parent().parent()).index(this));
				},
				function () {
					$(this).parent().removeClass("itemSub" + $(this).parent().prevAll().length);
					//$(this).parent().removeClass("item" + $('li', $(this).parent().parent()).index(this));
				}
			);
		}
		else {
			$("#promo3").find("a").hover(
				function () {
					$(this).parent().addClass("itemSubEn" + $(this).parent().prevAll().length);
					//$(this).parent().addClass("item" + $('li', $(this).parent().parent()).index(this));
				},
				function () {
					$(this).parent().removeClass("itemSubEn" + $(this).parent().prevAll().length);
					//$(this).parent().removeClass("item" + $('li', $(this).parent().parent()).index(this));
				}
			);
		}	
		
	}
	
	
	$("#promo2").find("a").hover(
		function () {
			$(this).parent().addClass("newsExtra" + $(this).parent().prevAll().length);
		},
		function () {
			$(this).parent().removeClass("newsExtra" + $(this).parent().prevAll().length);
		}
	);
}

var addLinkToLatest = function() {
	$("#promo3").find("h2 > span").wrap("<a href='/News/'></a>");
	/* $("#promo2").find("h2 > span").wrap("<a href='/News/Events/'></a>"); */
}

/*
var addHomePageClass = function() {
	$("#promo2").find("pre").each( function(){
		if ($(this).hasClass("homePage")) {
			$("body").addClass("homePage");
		}
	});
}


var removeFirstElementFromTheList = function() {
	var numberOfElements = $("#home-images").find("li");
	if (($(numberOfElements).size() > 0)) {
		$(numberOfElements).eq(0).remove();
	}
}

var wrapBGImages = function() {
	var BGLinks = [
				   "Projects/By-Name/A-E/Brewhouse-Yard/",
				   "Projects/By-Name/M-O/Marlowe-Academy/",
				   "Projects/By-Name/F-L/Liverpool-ONE/",
				   "Projects/By-Name/F-L/Glasgow-Science-Centre/",
				   "Projects/By-Name/P-Z/University-of-East-London/"
				   ];
	
	var arrayCounter = 0;
	$(".liveShowcase").find("li > img").each(function() {
		$(this).wrap("<a href='" + BGLinks[arrayCounter] + "'></a>");
		arrayCounter++;
	});
	
}

*/


var addSectionsToSearchResults4 = function() {
	$("#ResultArea").find("ol > li").each( function() {
		//$(this).append("<p class='resultSection'>News</p>");
		var fullLocation = $(this).find("a").attr("href");
		var eventsRegex = /\/Events\//
		var globalRegex = /\/Global\//
		var dutchRegex = /\/Netherlands\//
		var locationRegex = /\.\.\/(\w*)/
		var sectionName = locationRegex.exec(fullLocation);
		//console.log("sdsd" + eventsRegex.test(fullLocation));
		if(eventsRegex.test(fullLocation)) {
			$(this).append("<p class='resultSection Events'>Events</p>");
		}
		else if (globalRegex.test(fullLocation)) {
			$(this).append("<p class='resultSection Images'>Images</p>");
		}
		else if (dutchRegex.test(fullLocation)) {
			$(this).remove();
		}
		else {
			$(this).append("<p class='resultSection " + sectionName[1] + "'>" + sectionName[1] + "</p>");
		}
	});
}

var checkIfImageExists = function(imageURL) {
	var imgObj = new Image;
	imgObj.src = imageURL;
	if (imgObj.width > 0) {
		return true;
	}
	else {
		return null;
	}
		
}
/*
var addCustomThumbnails = function() {
	// lighting
	var section = ($("#breadcrumbs").find("li.selected > a").text()).toLowerCase();
	if (section == "lighting") {
		var varPagination = $(".pagination-pages").text();
		var paginationRegex = /1-9/
		var fileNameRegex = /(.*).jpg/
		if (paginationRegex.test(varPagination)) {
			$("#projects-content, #content-view-grid").find("img").each( function() {
				var fileNameNoExt = fileNameRegex.exec($(this).attr("src"));
				var newFileName = fileNameNoExt[1] + "_" + section + ".jpg";
				//checkIfImageExists(newFileName);
				$(this).attr("src", newFileName);		
				//console.log(newFileName);
			}); 
		}
	}
}
*/
var addCustomThumbnails = function() {
	var section = ($("#breadcrumbs").find("li.selected > a").text()).toLowerCase();
	var fileNameRegex = /(.*).jpg/i
		$("#projects-content, #content-view-grid").find("img").each( function() {
			var fileNameNoExt = fileNameRegex.exec($(this).attr("src"));
			var orgFileName = fileNameNoExt[1] + ".jpg";
			var newFileName = fileNameNoExt[1] + "_" + section + ".jpg";
			$(this).attr("src", newFileName);
			$(this).each(function(index){
				$(this).error(function() {
					$(this).unbind("error").attr("src", orgFileName);
				});
			});
		});
}



var checkLanguagePage = function() {
	if ($("#pageHeader > #lang-selection").length != 0){
		if (checkLanguageUrl()) {
			$("#lang-selection").find('a[title="Nederlands"]').addClass('selected');
		}
		else {
			$("#lang-selection").find('a[title="English"]').addClass('selected');
		}	
	}	
}


var animatedSubNav = function() {
	var subNav = $("#nav-sub");
	$(subNav).animate({opacity: 0.75}, 50);
	$(subNav).hover(
		function() {
			$(this).animate({
				opacity: 1
            	}, {duration: 300, queue: false});
			},
		function() {
			$(this).animate({
				opacity: 0.75
				}, {duration: 300, queue: false});
		}
	);
}

var h2BreakLine = function() {
	$("#nav-sub > h2").html("61/11 <br> Celebrating 50 Years.");
}

var paypalForAnniversaryBook = {
	searchString: 	'#paypalForAnniversaryBook',
	injectString: 		'<form action="https://www.paypal.com/cgi-bin/webscr" method="post">'+
						'<input type="hidden" name="cmd" value="_s-xclick">'+
						'<input type="hidden" name="hosted_button_id" value="GAYQQMTYLLZ3Q">'+
						'<table>'+
						'<tr><td><input type="hidden" name="on0" value="£28 plus delivery to:">\u00A328 plus delivery to:</td></tr><tr><td><select name="os0">'+
						'	<option value="UK delivery 5 GBP">UK \u00A328 (+ \u00A35 del.) \u00A333.00</option>'+
						'	<option value="Europe 7.50 GBP">Europe &pound;28 (+ &pound;7.50 del.) &pound;35.50</option>'+
						'	<option value="Worldwide 10 GBP">Worldwide &pound;28 (+ &pound;10 del.) &pound;38.00</option>'+
						'</select> </td></tr>'+
						'</table>'+
						'<input type="hidden" name="currency_code" value="GBP">'+
						'<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online." style="border: 0; margin: 10px 0 0 20px; width: 160px; height: 47px;">'+
						'<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">'+
						'</form>',
	replaceString:	'Buy the book directly from BDP using Paypal below, price includes postage and packing.',
	init:			function () {
//						var splitURL = window.location.href.split("?");
//						if ((splitURL.length > 1) && (splitURL[1]=="test"))
						$(this.searchString).text(this.replaceString).append(this.injectString).show();
						return false;
					}
}


var studiosDDMenu = function() {
	//var hoverArea = $('#nav-main a[title="Studios"]');
	//var hoverArea = $("#nav-main a[title=Studios]");
	
	$("#promo1").append("<div id=studiosMainNavDD> \
					   <ul> \
					   <li><a href='http://www.bdp.com/en/Studios/UK/'>UK locations</a></li> \
					   <li><a href='http://www.bdp.com/en/Studios/China/'>China</a></li> \
					   <li><a href='http://www.bdp.com/en/Studios/India/'>India</a></li> \
					   <li><a href='http://www.bdp.com/en/Studios/Dublin/'>Ireland</a></li> \
					   <li><a href='http://www.bdp.com/en/Studios/Netherlands/'>Netherlands</a></li> \
					   <li><a href='http://www.bdp.com/en/Studios/UAE/'>United Arab Emirates</a></li> \
					   </ul> \
					   </div>");
	var studioSubMenuElements = $("#studiosMainNavDD");
	$(studioSubMenuElements).hover(
					   function() {
						   $(this).prepend("<span>STUDIOS</span>")
						   $(this).addClass("studiosMenuOn");
						   //$(this).animate({
							//	height: 50,
							//	width: 128									   
						 //  }, {duration: 'fast'});
						},
					   function() {
						   $(this).find("span").remove();
						   $(this).removeClass("studiosMenuOn");
						   //$(studioSubMenuElements).hide();
						}
					   ).click(function() {
							window.location.href = 'http://www.bdp.com/en/Studios/';
					   });
}

var reorderChinePeople = function() {
	$items = $('#content-view-grid >li');
	my_array = [ $items.get(3), $items.get(0), $items.get(2), $items.get(5), $items.get(6), $items.get(1), $items.get(4) ];
	jQuery.each(my_array, function() {
		$('#content-view-grid').append(this);
	});
}

var reorderIndiaPeople = function() {
	$items = $('#content-view-grid >li');
	my_array = [ $items.get(1), $items.get(3), $items.get(5), $items.get(0), $items.get(2), $items.get(4) ];
	jQuery.each(my_array, function() {
		$('#content-view-grid').append(this);
	});
}

var reorderUAEPeople = function() {
	$items = $('#content-view-grid >li');
	my_array = [ $items.get(4), $items.get(2), $items.get(1), $items.get(0), $items.get(3), $items.get(5) ];
	jQuery.each(my_array, function() {
		$('#content-view-grid').append(this);
	});
}

$(document).ready( function () {

		if ($('body').hasClass('main')) {
			studiosDDMenu();
		}
		
		$(".job-detail #displayItem").find("a").attr("href", "http://www.bdp.com/en/News/2011/Building-Awards-Shortlist-Announced/");
		
		if (!$('body').hasClass('sub') && $("#ResultArea")) {
			addSectionsToSearchResults4();
		}
		
		if ($('body').hasClass('pt2575FullSizeImages')) {
			animatedSubNav();	
		}
		
		if ($('body').hasClass('celebrating50Years')) {
			h2BreakLine();	
		}
				
		checkLanguagePage(); //add class 'selected' to the selected language
		
		//addHomePageClass();
		addClassesToFeaturedNewsItems();
		addLinkToLatest();
		$("#displayItem").hide;
		
		if ($('body').hasClass('thumbSwop')) {
			addCustomThumbnails(); //custom thumbnails for sector/services project pages
		}
		//setTimeout("wrapBGImages()", 2500);
		// apply a class to header li's based on the text appearing in them, so text replacement can be activated
        
        // regex to catch html tags and entities, as well as any non alphabetical or numerical characters
        headerRegEx = new RegExp(/(<\/?.*?>)|(\&.*?;)|\W/gi);

        
/*        $("#pageHeader #nav-main ul li").each(  function () {
            var text = $(this).find("a").html().replace(headerRegEx, "").toLowerCase();
            $(this).attr("id", "nav-main-" + text).addClass("nav-main-IR");
        });
*/        
        $("#nav-sub").each(  function () {
            var text = $(this).find("h2").html().replace(headerRegEx, "").toLowerCase();
            $(this).addClass("nav-sub-" + text);
        });
        
        selectorText = function (inText) {
            if (typeof inText == "undefined") return "";
            var myText = inText.toString();
            return myText.replace(headerRegEx, "").toLowerCase();
        }
        
		$(".nav-sub-india").find("[title=New Delhi]").parent().remove();
		$(".nav-sub-china").find("[title=Shanghai]").parent().remove();
        $(".nav-sub-uk").find("[title=United Kingdom]").parent().remove();
		$(".nav-sub-uae").find("[title=Abu Dhabi]").parent().remove();
		wrapColumns();
		
		// addition for removing Projecten link from the sub menu for BDP.Khandekar sub-site
		if (($('body').hasClass('sub')) || ($("#nav-sub").hasClass("nav-sub-projecten"))) {
			var projectenLink = $("#nav-sub-list > ul").find("a[title='Projecten']");
			$(projectenLink).parent().parent().parent().hide();	
		}
		// end of addition for removing Projecten link from the sub menu for BDP.Khandekar sub-site
				
		$("div.nav-sub-videos li.nav-sub-col").find("[title=Videos]").parent().remove();
				
		$(".additionalInfo").append("<p>Total word count: <span id='display_count'>0</span> of  " + max_words + "</p>");
		$(".wordsLimit").wordCount();
       
        $("#people-search-form").show(0);

        if (typeof showcaseCFG == "object") {
            var initCFG = {           
                displayTime: 4000,
                targetSearch: null,
                repeat: true,
                showInfo: true,
                showNav: true,
                showcaseMode: true,
                displayArea: "#displayItem",
                fadeOutArea: "#displayFadeOut",
                fadeTime: "fast",
                cacheAllImages: true,
                displayInfoClass: null, //".displayInfo",
                displayInfoBG: ".infoBackground",
                displayInfoOpacity: 0.3,
                displayInfo: function  (imageRef) {return '<div class="displayInfo"><ul>' 
/*                                                    + (imageRef.imageCaption ? '<li class="infoCaption">' + imageRef.imageCaption + '</li>' : '') 
                                                    + (imageRef.imageDescription ? '<li class="infoDescription">' + imageRef.imageDescription + '</li>' : '')*/
                                                    + (imageRef.imageCopyright ? '<li class="infoCopyright">' + imageRef.imageCopyright + '</li>' : '')
                                                    + '</ul><p class="infoBackground">&nbsp;</p></div>'}
            }
        
            initCFG = apply(initCFG, showcaseCFG || {});
//            initCFG.showcaseConfig = showcaseCFG;
            STviewer.showcaseConfig = STviewer.config; // hopefully not needed
            // set positioning on the container UL to relative
            $(initCFG.displayArea).find("ul").addClass("liveShowcase");
            
            // if a fadeOutArea exists, remove it as we don't need it          
            $(initCFG.fadeOutArea).remove();
            
            $("body").initSTviewerJS(initCFG);
        } else if (typeof imageViewerCFG == "object") {
            var initCFG = {
                pvMode: true,
                displayTime: 8000,
                targetSearch: null,
                repeat: true,
                displayArea: "#pvDisplayArea",
                fadeOutArea: "#pvFadeOut",
                fadeTime: 1000,
                cacheAllImages: true,
                loadingGraphic: '<img src="images/loading-light.gif" width="32" height="32" border="0" alt="loading" />'
                
            }
            initCFG = apply(initCFG, imageViewerCFG || {});
//            initCFG.xshowcaseConfig = imageViewerCFG;
/*           
            if ($(initCFG.fadeOutArea).length == 0) {
                var fadeOutID = initCFG.fadeOutArea.replace(/^#/, "");
                $(initCFG.displayArea).find("ul").html('<li id="' + fadeOutID + '"></li>');
            }
            */
            $("#project-accessible-images").addClass("js");
            $("body").initSTviewerJS(initCFG);
        }
		

    if (jQuery.browser.msie) {
        // "tweaks" for IE browsers
        
        if (jQuery.browser.version == "6.0") {
            // footer
            $("#pageFooter>ul>li:first").addClass("firstFooterItem");
        
        
        }
    
    
    }
	paypalForAnniversaryBook.init();
	
	if ($('body').hasClass('cPeople')) {
		reorderChinePeople();
	}
	
	if ($('body').hasClass('iPeople')) {
		reorderIndiaPeople();
	}
	
	if ($('body').hasClass('uPeople')) {
		reorderUAEPeople();
	}
	
	if ($("#publicaties").length != 0) {
		$("#pageContent").addClass("news-homepage");
	}


});


