// client-side scripts

function clearText(thefield) {
if (thefield.defaultValue==thefield.value) {
   thefield.value = '';
   }
}
function putText(thefield) {
if (thefield.value=='') {
   thefield.value = thefield.defaultValue;
   }
}

function ow(inURL) {
var sURL = inURL.toLowerCase();
var sUserAgent = navigator.userAgent.toLowerCase();
var isOp = (sUserAgent.indexOf('opera')!=-1)?true:false;

var winName = "_blank";
var winProps = "";

var prompt_user = 0; // default to prompting
if ((sURL.indexOf('luton.gov.uk') > -1) || (sURL.indexOf('hyperdev') > -1) || (sURL.indexOf('10.65.4.57') > -1))// i.e. it DOES contain that string
	{
	// look to see if source coming from a known remote document store
	if ((sURL.indexOf('external%20links') == -1) )
		{
		prompt_user = 0;    // don't prompt
		}
	}
	
if (sURL.indexOf('victoriaforms.com/cf') > -1) 
	{
	winProps = 'resizable=yes, scrollbars=no, height=550, width=795, left=0, top=0, location=1';
	winName = 'newwnd';
	}
	
if (prompt_user == 1)
	{
	alert("You are now leaving our web site. \nLuton Council is not responsible for the content of external internet sites\n\nIf the new window does not open, your browser's pop-up blocker may need to be turned off for our site\nTry holding down Control (CTRL) when you click the link");
	}

if ((sURL.indexOf('/cmsadmin/forms') > -1) || (sURL.indexOf('secure.luton.gov.uk') > -1) )
	{
	winProps = 'copyhistory=no, scrollbars=yes, toolbar=no, location=no, status=yes, directories=no, menubar=no, resizable=yes, width=750, height=600, left=0, top=0';
	}

if ( sURL.indexOf('.w3.org') > -1 || sURL.indexOf('.oed.com') > -1 )
	{
// if linking to some sites, don't use window.open here, allow href to kick in and provide the referrer field for us
	return true;
	}

var xwh;
if (winProps == "") 
	{
	xwh=window.open(inURL,winName);
	}
else
	{
	xwh=window.open(inURL,winName,winProps);
	}
if(xwh && !isOp) { xwh.focus(); }

var returnVal = (xwh)?false:true;

//if window has opened OK, we return false to prevent the normal link href from firing
// otherwise, we return false, which will let the href take over

//alert("returning " + returnVal);
//if (returnVal)
//	{
//	alert("Popups appear to be blocked for this site.\nPlease configure your popup blocker to allow popups on this site, or try the link again whilst holding down Control");
//	}
return returnVal;
}

// With onkeypress event, this verifies 'Enter' key and ignores other presses
function checkKeyPress(iElement,iEvent)
{
// set return value to true to allow keypress to work in browser if it's one we're not interested in
var returnval = true;
if(iEvent.keyCode==13 && iElement.onclick)
	{
		iElement.onclick();
// if enter pressed, then we'll fire off the onclick here, 
// and prevent the browser from firing off a second time in some popular browsers
		returnval = false;
	}
return returnval;
}

// pulled out from faq.xml
function sendForm(thisFormName)
{
   document.forms[thisFormName].submit();
     return true;		
}

function checkVote()
{
  if ((document.voteform.vote[0].checked == false) && (document.voteform.vote[1].checked == false) && (document.voteform.vote[2].checked == false)) 
  {
	alert("Please choose a voting option.");
	return false;
  }
  if(!document.voteform.your_email_adress.value)
  {
	alert("Please enter your e-mail address.");
	document.voteform.your_email_adress.focus();
	return false;
  }
}



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// client-side scripts

function addLoadEvent(func) {

var oldonload = window.onload;
if (typeof window.onload != 'function')
	{
	window.onload = func;
	} else {
	window.onload = function() {
		if (oldonload)
			{
			oldonload();
			}
		func();
		};
	}
}

function writeIt() {

var meta = document.createElement('div');

meta.id = 'toggleBlock';
meta.style.position = "absolute";
meta.style.top = "0";
meta.style.right = "0";
//meta.style.width = "260px";
meta.style.background = "#FCE2B4";
meta.style.border = "0 solid #000";
meta.style.padding = "0";
meta.style.MozOpacity = "1.0";
meta.style.zIndex = 100;

var a = meta.appendChild( document.createElement('span') );

var newhost = document.location.href;
var replacewith = "90";
//alert(document.location.host);
if (document.location.host == "www.luton.gov.uk:98") {
	replacewith = "80"; }
newhost = newhost.replace(/98/,replacewith);

var text = "<span style='display:block; padding: 2px; '>Show regular version of this page (port " + replacewith + ")</span>";

var newURL = newhost;

output = "<a href='" + newURL + "' target='_blank'>" + text + "</a>";

meta.innerHTML = output;
a.style.display = "block";

document.body.insertBefore(meta, document.body.firstChild);

}

// start of onLoad function
$(document).ready( function() {

	var useJQ = true;

	if (document.location.search && document.location.search.indexOf("jq") > 0 ) {
		useJQ = false; } //  alert("jq = disabled")

	if (useJQ == true) {
		// for each plainBox and centerBox, insert a hyperlink to show/hide this section
		$('#quicklinks,#newsheading,#diol,#lutonline,#sparehead,#ptopics,#cal,#explore,#rLinks,#rNews').each( function () {
			var text = "hide";
			var classtype = "";
			if ( $.cookie(this.id) == "hidden" ) { // found this id in cookies so need to hide it
				$(this).children('div').hide();
				text = "show";
				classtype = " gone";
			}
			text = "<div class='showhide" + classtype + "'>" + text + "</div>";

			// $("#" + this.id).children('h2').prepend(" <div class=\"showhide\" >[<a href=\"#\" title=\"Show / hide this panel of information\">" + text + "</a>]</div>");
			// nasty change to fix bug in safari 2.0.4 on Mac... grr!
			$(this).children('h2').each(function () {
				var curr = this.innerHTML;
				curr = text + curr;
				this.innerHTML = curr;
				}); 
			//" <span class=\"showhide\" >[<a href=\"#\" title=\"Show / hide this panel of information\">" + text + "</a>]</span>");
		}); //each

		// for each of the items just added, add an 'onclick' function to toggle the contained DIV
		$('div.showhide').click(function() {		
		// toggle the sibling div(s) visibility by sliding
			$(this).parent().next('div').slideToggle();
			var thisID = $(this).parent().parent().attr('id'); // get id of parent block so that we can update a named cookie
			$(this).toggleClass('gone');
			if ( $(this).hasClass('gone') ) { // need to set cookie to prevent showing this div in future
				$(this).text('show');
				$.cookie(thisID, "hidden", { path: '/', expires: 999 });
			} else { // need to clear cookie to permit showing this div in future
				$(this).text('hide');
				$.cookie(thisID, null, { path: '/'});
			}
			return false;
		});

		// start of show/hide today's events
		// add the currect button into the html
		$('#todayEvents').each( function () {
			var text = "hide";
			var classtype = "";
			if ( $.cookie("todayEventsButt") == "hidden" ) { // need to hide it
				$("#calEvents").hide();
				text = "show";
				classtype = " gone";
			}
			text = "<div class='showhide" + classtype + "' id='todayEventsButt' >" + text + "</div>";

			$('#todayEvents').parent().each(function () {
				var curr = this.innerHTML;
				curr = text + curr;
				this.innerHTML = curr;
			});  
		});

		// add the onclick function
		$('#todayEventsButt').click(function()
		{
			// toggle the sibling div(s) visibility by sliding
			$('#calEvents').slideToggle();

			var thisID = "todayEventsButt";
			$(this).toggleClass('gone');
			if ( $(this).hasClass('gone') )
			{ // need to set cookie to prevent showing this div in future
				$(this).text('show');
				$.cookie(thisID, "hidden", { path: '/', expires: 999 });
			}		
		else
			{ // need to clear cookie to permit showing this div in future
				$(this).text('hide');
				$.cookie(thisID, null, { path: '/'});
			}
		return false;
		});
		// end of show/hide today's events

		// start of roll up for mainpic
		$('#mainpic').each( function () {
			var classtype = "";
			var text = "hide";
			if ( $.cookie("mainpic") == "hidden" ) { // found this id in cookies
				$(this).addClass("picgone").css( { height: "32px" });
				text = "show";
				classtype = " picgone"
			}
			text = "<div class='showhide" + classtype + "' id='pichide'>" + text + "</div>";

			//      $("#" + this.id).children('h2').prepend(" <div class=\"showhide\" >[<a href=\"#\" title=\"Show / hide this panel of information\">" + text + "</a>]</div>");
			// nasty change to fix bug in safari 2.0.4 on Mac... grr!
			$('#picCaption').each(function () {
				var curr = this.innerHTML;
				curr = text + curr;
				//	alert(curr);
				this.innerHTML = curr;
			}); 
		}); //each

		// for each of the items just added, add an 'onclick' function to toggle the contained DIV
		$('#pichide').click(function() {
			// toggle the sibling div(s) visibility by sliding
			//      $('#mainimg').slideToggle();
			var thisID = "mainpic";
			$(this).toggleClass('picgone');
			if ( $(this).hasClass('picgone') ) {
				$('#mainpic').toggleClass("picgone").animate( { height: "32px" } );
				$(this).text('show');
				// need to set cookie to prevent showing this div in future
				$.cookie(thisID, "hidden", { path: '/', expires: 999 });
			} else {
				$('#mainpic').toggleClass('picgone').animate( { height: "200px"} );
				$(this).text('hide');
				// need to clear cookie to permit showing this div in future
				$.cookie(thisID, null, { path: '/'});
			}
			return false;
		});
		// end roll up for mainpic
    }

    //if ( document.location.host == "www.luton.gov.uk" ) {
	//	scanforlinks(); }

	if ($('#flickrCont').length > 0 ) { doFlickr(); }
	
	//alert(document.location.host);
	//if ( document.location.host == "hyperdev.central.luton:98" ) {
		jScanForLinks();
	//}
	
  }); // end ready function


function doFlickr() {
  
	var tag = $('#flickrCont').attr('class');
	tag = tag.replace(/^XX/,'');
//	alert("Flickr tag found: " + tag);
	
	var url = "http://api.flickr.com/services/feeds/photos_public.gne?id=11403452@N02&lang=en-us&format=json&tags=" + tag + "&jsoncallback=?";
  
	$.getJSON(url, function(data)
		{
		
		var picArray = [];
		
		for (var i=0;i< data.items.length;i++) {
		
			var pic = {};
			pic.title = data.items[i].title;
			pic.media = data.items[i].media;
			pic.taken = data.items[i].date_taken;
		
			picArray.push( pic );

		}
		
		picArray.sort( picSort );
				
		//$.each(data.items, function(i,item)				
		$.each(picArray, function(i,item)
			{
				if ( i > 17 ) { return false; };
				var smallImg = item.media.m.replace(/_m\./,"_s.");
				var origImg = item.media.m.replace(/_m\./,".");
				$("<img/>").attr( {src: smallImg, alt: item.title}).appendTo("#flickrImages").wrap("<a href=\"" + origImg + "\" class=\"flickrT\" title=\"" +  item.title + "\"></a>");
			});

			$('#flickrImages a').lightBox({
				fixedNavigation: true,
				imageLoading: '/wavemaster.internal/styles/common/jqlb/lightbox-ico-loading.gif',
				imageBtnClose: '/wavemaster.internal/styles/common/jqlb/lightbox-btn-close.gif',
				imageBtnPrev: '/wavemaster.internal/styles/common/jqlb/lightbox-btn-prev.gif',
				imageBtnNext: '/wavemaster.internal/styles/common/jqlb/lightbox-btn-next.gif'
			});
		});
		
}
  

function showhide() {

var curr = $('#colThree').css("display");

if (curr == 'none')
	{
	$('#colTwo').animate({width: '590px'}, 'slow', function() {
		$('#colThree').fadeIn('slow');
		} );
	}
else
	{
	$('#colThree').fadeOut('slow', function() {
		$('#colTwo').animate({width: '780px'}, 'slow');
		} );
	}

}


//	This javascript tags file downloads and external links in Google Analytics.
//	You need to be using the Google Analytics New Tracking Code (ga.js) 
//	for this script to work.
//	To use, place this file on all pages just above the Google Analytics tracking code.
//	All outbound links and links to non-html files should now be automatically tracked.
//
//	This script has been provided by Goodwebpractices.com
//	Thanks to ShoreTel, MerryMan and Colm McBarron
//
//	www.goodwebpractices.com
//	VKI has made changes as indicated below.								

function startListening (obj,evnt,func) {
        if (obj.addEventListener) {
                obj.addEventListener(evnt,func,false);
        } else if (obj.attachEvent) {
                obj.attachEvent("on" + evnt,func);
        }
}

function trackMailto (evnt) {
        var href = (evnt.srcElement) ? evnt.srcElement.href : this.href;
        var mailto = "/mailto/" + href.substring(7);
        if (typeof(pageTracker) == "object") { pageTracker._trackPageview(mailto); }
}

function trackExternalLinks (evnt) {
        var e = (evnt.srcElement) ? evnt.srcElement : this;
        while (e.tagName != "A") {
                e = e.parentNode;
        }
        var lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname;
        if (e.search && e.pathname.indexOf(e.search) == -1) { lnk += e.search; }
        if (e.hostname != location.host) { lnk = "/external/" + e.hostname + lnk; }
        if (typeof(pageTracker) == "object") { pageTracker._trackPageview(lnk); }
}

function scanforlinks () {
var total = 0;
var myhref = "";

var myhost = location.host.replace(/^([^:]*):.*/,"$1");

if (document.getElementsByTagName)
	{
        // Initialize external link handlers
        var hrefs = document.getElementsByTagName("a");
        for (var l = 0; l < hrefs.length; l++)
		{
		// try {} catch{} block added by erikvold VKI
		try
			{
	                //protocol, host, hostname, port, pathname, search, hash
	                if (hrefs[l].protocol == "mailto:") {
	                        startListening(hrefs[l],"click",trackMailto);
				total++;
	                } else if (hrefs[l].hostname == myhost) {
	                        var path = hrefs[l].pathname + hrefs[l].search;
				var isDoc = path.match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/);
	                        if (isDoc) {
	                                startListening(hrefs[l],"click",trackExternalLinks);
					total++;
	                        }
	                } else {
				myhref = myhref + hrefs[l].hostname + "\n";
	                        startListening(hrefs[l],"click",trackExternalLinks);
				total++;
	                }
			}
		catch(e){
					continue;
			}
	        } //try
	} // for
//	alert("total links = " + total + ":\n" + myhref);
} // func

function jScanForLinks() {
	var i = 0;
	var prot;
	var link;
	var href;
	var linkhost;
	
	//$("#picCaption a").bind('click', function ()
	$("#mainpic a").bind('click', function ()
		{
			var url = $(this).attr('href');
//			alert("Clicked banner link:" + url);
			if (pageTracker)
			{
				pageTracker._trackEvent('Advert', 'Banner', url);
			}
		} );

	$("#sparebody a").bind('click', function ()
		{
			var url = $(this).attr('href');
//			alert("Clicked Campaign link:" + url);
			if (pageTracker)
			{
				pageTracker._trackEvent('Advert', 'Campaign', url);
			}
		} );

	$("#rAdvert a").bind('click', function ()
		{
			var url = $(this).attr('href');
//			alert("Clicked Advert link:" + url);
			if (pageTracker)
			{
				pageTracker._trackEvent('Advert', 'Advert', url);
			}
		} );
		
	$("a").each( function()
	{
		link = $(this);
		href = link.attr('href');
		linkhost = link.attr('hostname')
		if (href) { // only want links with href destinations
			prot = link.attr('protocol');
			//alert(href + "  " + link.attr("protocol"));
			if (prot == "mailto:")
			{ // email link
				$(this).bind('click', function()
				{
					if (pageTracker)
					{
						var url = $(this).attr('href');
						url = url.replace(/^mailto./,"");
					//	alert("Clicked email: '" + url + "'");
						pageTracker._trackEvent('Email link', url);
					}
				});
			}
			else 
				if (linkhost == location.hostname)
				{ 	// link on local server
					//var path = hrefs[l].pathname + hrefs[l].search;
					var path = this.pathname + this.search;
					var isDoc = path.match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/);
					if (isDoc) {
						$(this).bind('click', function()
						{
							if (pageTracker)
							{
								// alert("Clicked known mime type: " + $(this).attr('href'));
								pageTracker._trackEvent('Filetype link', $(this).attr('href'));
							}
						});				
						}
				}
				else 
				{ // remote link
					$(this).bind('click', function()
						{
						if (pageTracker)
						{
							//	alert("Clicked external link: " + $(this).attr('href'));
								pageTracker._trackEvent('External link', $(this).attr('href'));
						}
						}).addClass("externalLink");
				}
			}	
		
		return true;
	
	});

}

function doNHS() {

	var tag = $("#rNHS").attr('class');
	tag = tag.replace(/^.*XX/,'');
	
	$("#rNHSdiv").html("Loading news items for '" + tag + "' <img src=\"/wavemaster.internal/styles/luton/wait.gif\" alt=\"Loading image\">"); 
	
	var scriptUrl = "http://query.yahooapis.com/v1/public/yql?q=USE%20'http%3A%2F%2Fwww2.luton.gov.uk%2Frss%2FnhsNews2.xml'%20AS%20nhsNews%3B%20SELECT%20*%20FROM%20nhsNews%20WHERE%20topic%3D'";
	scriptUrl = scriptUrl + tag;
	scriptUrl = scriptUrl + "'&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=parseNews";
	var objTransaction = YAHOO.util.Get.script(scriptUrl); 
	
}

function parseNews( res ) {

if ( (res.query.results == null) || (res.query.count<2))
	{
	$("#rNHSdiv").html("No records found");
	return false;
	}
	
var ul = $("<ul>");
var entries = res.query.results.NewsComponent;
for (var i=0; i<entries.length; i++)
	{
		var entry = entries[i];
		ul.append("<li><a href=\"" + entry.NewsItemRef.NewsItem + "\" title=\"" + entry.NewsLines.SlugLine + "\">" + entry.NewsLines.HeadLine + "</a></li>");
	};
	
	$("#rNHSdiv").html(ul); 

}
function picSort(a,b) {

	return a.taken > b.taken;

}
