// 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/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 addClassesToFeaturedNewsItems = function() {
	//var ItemsCount = $("#promo3").find("li").length;
	/*
	var counter = 1;
	$("#promo3").find("li").each(function() {
		$(this).attr("class","item"+counter);
		counter++;
	});
	*/
	$("#promo3").find("li").hover(
		function () {
			$(this).addClass("item" + $('li', $(this).parent()).index(this));
		},
		function () {
			$(this).removeClass("item" + $('li', $(this).parent()).index(this));
		}
	);
	$("#promo2").find("li").hover(
		function () {
			$(this).addClass("event1");
		},
		function () {
			$(this).removeClass("event1");
		}
	);
}

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++;
	});
	
}

*/

$(document).ready( function () {

		//addHomePageClass();
		addClassesToFeaturedNewsItems();
		addLinkToLatest();
		$("#displayItem").hide;
		//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-uk").find("[title=United Kingdom]").parent().remove();
		wrapColumns();
		
		$("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");
        
        
        }
    
    
    }

});

