// Avoid FOUC
var elements = document.getElementsByTagName("html");
elements[0].className += " JSEnabled"

panelHandler = {
    loadPanel : function(panelName, id, params)
    {
        params.id = id;

        url = '/resources/ph/'+panelName+'/';

        this.load(url, params);
    },

    load : function (url, params)
    {
        $.ajax(
            {
                type: 'GET',
                url: url,
                dataType: 'json',
                data: params,
                success: panelHandler.ajaxSuccess,
                error: function(a,b,c) { /*console.log(a,b,c)*/ }
            }
        );
    },
    ajaxSuccess : function (result)
    {
        id = result.id;

        try
        {
            $(id).html(result.html);
        }
        catch (err)
        {
            // the dom element doesn't exist, so exit
            return;
        }

        switch(result.panelName)
        {
        case 'EventsLiveTravelPanel':
            panelHandler.liveTravel(result, id);
            break;
        case 'MostPopularDataPanel':
            panelHandler.mostPopular(result, id);
            break;
        }
        attachClearOnFocus();
        attachClearOnSubmit();
    },
    liveTravel : function(data, id)
    {

        $(id).html(data.html.html);

        // current time
        dateObj = new Date();
        currentTime = dateObj.getTime();

        //different times
        // morning starts at 7:30
        morningStart = new Date();
        morningStart.setHours(7, 30, 00);

        // and ends at 9:30
        morningEnd = new Date();
        morningEnd.setHours(9, 30, 00);

        // evening starts at at 4 30
        eveningStart = new Date();
        eveningStart.setHours(16, 30, 00);

        // and ends at 6 30
        eveningEnd = new Date();
        eveningEnd.setHours(18, 30, 00);


        inTime = false;
        // check if we're in a time period'
        if ((currentTime > morningStart.getTime() &&
             currentTime < morningEnd.getTime()) ||
            (currentTime > eveningStart.getTime() &&
             currentTime < eveningEnd.getTime() ))
        {
            inTime = true;
        }


        if (data.html.hasImportantIncidents && inTime)
        {
            $(".whatsTravel").tabs({selected: 1});
        }
        else if (data.html.severeIncidents.length > 0)
        {
            $(".whatsTravel").tabs({selected: 1});
        }
        else if (data.html.noIncidents)
        {
                $(".whatsTravel").tabs();
        }
        else
        {
            if ($('#li-first').html() == '1')
            {
                $(".whatsTravel").tabs({selected: 1});
            }
            else
            {
                $(".whatsTravel").tabs();
            }
        }
        if (data.html.severeIncidents.length > 0)
        {
            $.each(data.html.severeIncidents, function (key, value)
            {
                container = $('<div class="art"></div>');
                container2 = $('<div class="artOverride"></div>');
                link = $('<a></a>').attr('href', '/li/traffic.detail.'+value.id);

                // create the headline with a h4
                headline = $('<h2></h2>');

                // the traffic em sits inside the headline
                traffic = $('<em class="breaking"></em>').html('Traffic Alert');
                headline.append(traffic);
                
                // add the headline texti
                headline.append(value.route+', '+value.area);
                incidentDelta = $('<p class="update"></p>').html('Last updated '+panelHandler.calcDelta(value.update_time));
                var description = $('<p></p>').html(value.message);

                cameraLink = '';
                if (value.camera_ids != null)
                {
                    cameraLink = $('<p></p>');
                    cameraLinkA = $('<a class="trafficCamLink"></a>').attr('href', '/li/traffic.detail.'+value.id).html('View live traffic camera');
                    cameraLink.append(cameraLinkA);
                }

                link.append(headline, incidentDelta, description, cameraLink);

                container2.append(link);
                container.append(container2);

                try
                {
                    $('#trafficupdatesinarticle').append(container);
                }
                catch (err)
                {
                }

            });
        }

    },
    mostPopular: function(data)
    {
        $.each(data.html, function(g, f)
        {
            container = $('<div></div>');
            container.append($('<h5></h5>').html(f.title));
            ol = $('<ol></ol>');
            $.each(f.data, function (i, h)
            {
                li = $('<li></li>');
                href = $('<a></a>').attr('href', h.link);
                if (h.show_count)
                {
                    href.html(h.headline + ' ('+h.count+')');
                }
                else
                {
                    href.html(h.headline);
                }

                li.append(href);

                if (h.show_delta_and_cat)
                {
                    categoryLink = $('<a></a>').attr('href', h.category_link).html(h.category);
                    deltaStr = panelHandler.calcDelta(h.date_posted);
                    delta = $('<span></span>').html(' ('+deltaStr+' in ');
                    delta.append(categoryLink);
                    delta.append(')');
                    li.append(delta);
                }
                ol.append(li);
            });
            if (f.title == "Most recent")
            {
                l = $('<li><a href="/today/" class="bold">More from today &#187;</a></li>');
                ol.append(l);
            }
            container.append(ol);
            $('#'+f.id+'_content').append(container);
        });
    },
    calcDelta: function(timestamp)
    {
        n = Math.round(new Date().getTime() / 1000);
        delta = n - timestamp;
        if (delta < 60)
        {
            return delta + ' seconds ago';
        }

        delta = parseInt(delta / 60)

        if (delta < 60)
        {
            s = ((delta == 1)) ? '':'s';
            return delta + ' minute'+s+' ago'
        }
        delta = parseInt(delta / 60)

        if (delta < 24)
        {
            s = (delta == 1) ? '':'s';
            return delta + ' hour'+s+' ago'
        }
        delta = parseInt(delta / 24)
        s = (delta == 1) ? '':'s';
        return delta + ' day'+s+' ago'
    }

}

$(document).ready( function (){loadBisDir()});

function loadBisDir()
{
    if ($('#businessdircontext').length < 1)
    {
        return;
    }

    context = $('#businessdircontext').html();

    if (context.length < 1 || context === 'Unknown')
    {
        url = '/trade_directory/supers/5';
    }
    else
    {
        url = '/trade_directory/context/'+context;
    }

    $.ajax(
        {
            type: 'GET',
            dataType: 'json',
            url: url,
            success: function(e) {
            context = $('#businessdircontext').html();
            // if we have no results and we have a valid context, load it again
            // with no context, activating the random
            if (e == null && context != '' && context != 'Unknown')
            {
                // clear the context from the dom
                $('#businessdircontext').html('');
                loadBisDir();
                return;
            }

            $.each(e, function(g, f)
                {
                    category = f.categories.shift();

                    subcon = $('<li></li>');

                    // create the title
                    titleEl = $('<h5></h5>');
                    url = '/trade_directory/advert/'+category.tokenisedname+'/'+f.id+'/'+encodeURI(f.serviceName)+'?ref=ft';
                    titleLink = titleEl.append($('<a></a>').attr('href', url).html(f.serviceName));

                    // create the logo
                    if (f.logoId !== null)
                    {
                        logoUrl = '/resources/images/'+f.logoId+'/';
                        logoImg = $('<img />').attr('src', logoUrl).attr('alt', f.serviceName).attr('width', 60);
                        logoLink = $('<a></a>').attr('href', url);
                        logoLine = $('<p></p>').addClass('bizColLogo');
                        logoLink.append(logoImg);
                        logoLine.append(logoLink);
                        subcon.append(logoLine);
                    }

                    // create the more link
                    moreLink = $('<a></a>').attr('href', url).html('View details »');
                    moreLine = $('<p></p>').addClass('bizColDetails').append(moreLink);

                    // create the category
                    catLinkUrl = '/trade_directory/search/category/'+category.tokenisedname+'?ref=ft';
                    catLink = $('<a></a>').attr('href', catLinkUrl).html('More '+category.displayname);
                    cat = $('<p></p>').addClass('bizColMore').append(catLink);

                    subcon.append(titleLink);
                    subcon.append(moreLine);
                    subcon.append(cat);

                    $('#bizdir_content').prepend(subcon);
                });
            },
            error: function (a, b, c) {$('#businessdircontext').remove();}
        });

}

// dynamically create a brightcove player
function createBc(params, target)
{
    // no brightcove?
    if(brightcove == undefined)
    {
        if (console)
        {
            console.log('You must include the brightcove experience js');
        }

        return;
    }

    player = brightcove.createElement("object");
    player.id = "a"+target;
    for (key in params)
    {
        parameter = brightcove.createElement("param");
        parameter.name = key;
        val = params[key];
        if (typeof val == "function")
        {
            val = val();
        }
        parameter.value = val;
        player.appendChild(parameter);
    }
    playerContainer = document.getElementById(target);
    brightcove.createExperience(player, playerContainer, true);
}



function write_html(msg,id)
{
    $('#'+id).html(msg);
}
function showPic(whichpic)
{
    var source = whichpic.getAttribute('id');
    var mainPic = parent.document.getElementById('picsNtxt');
    mainPic.setAttribute('class',source);
}

function showTxt(whichtxt)
{
    var source = whichtxt.getAttribute('class');
    var mainTxt = parent.document.getElementById('para');
    mainTxt.setAttribute('class',source);
}

function revertTxt(prevtxt)
{
    var source = prevtxt.getAttribute('id');
    var thetxt = parent.document.getElementById('para');
    thetxt.setAttribute('class',source);
}

function popUp(strURL, strWidth, strHeight, otherOptions)
{
    var strOptions="";
    strOptions="'width="+strWidth+",height="+strHeight+","+otherOptions+"'";
    window.open(strURL, 'newWin2', strOptions);
}


function panelSwitcher(switchto,divIdOne,divIdTwo,divIdThree,firstLink,secondLink,thirdLink)
{
    // switchto MUST be one of (first|second), referring to itself(link)
    // switcher links MUST have IDs (link_one|link_two)
    var firstPanel  = document.getElementById(divIdOne);
    var secondPanel = document.getElementById(divIdTwo);
    var thirdPanel = document.getElementById(divIdThree);
    var firstLink   = document.getElementById(firstLink);
    var secondLink  = document.getElementById(secondLink);
    var thirdLink  = document.getElementById(thirdLink);


    switch(switchto)
    {
        case 'third':
            firstPanel.style.visibility     = 'hidden';
            firstPanel.style.display        = 'none';
            secondPanel.style.visibility    = 'hidden';
            secondPanel.style.display       = 'none';
            thirdPanel.style.visibility     = 'visible';
            thirdPanel.style.display        = 'block';
            firstLink.className             = 'off';
            secondLink.className            = 'off';
            thirdLink.className             = 'active_on';
            break;
        case 'second':
            firstPanel.style.visibility     = 'hidden';
            firstPanel.style.display        = 'none';
            secondPanel.style.visibility    = 'visible';
            secondPanel.style.display       = 'block';
            thirdPanel.style.visibility     = 'hidden';
            thirdPanel.style.display        = 'none';
            firstLink.className             = 'off';
            secondLink.className            = 'active_on';
            thirdLink.className             = 'off';
            break;
        case 'first':
            firstPanel.style.visibility     = 'visible';
            firstPanel.style.display        = 'block';
            secondPanel.style.visibility    = 'hidden';
            secondPanel.style.display       = 'none';
            thirdPanel.style.visibility     = 'hidden';
            thirdPanel.style.display        = 'none';
            firstLink.className             = 'active_on';
            secondLink.className            = 'off';
            thirdLink.className             = 'off';
            break;
    }
}

function panelSwitcher2(switchto,ids)
{
    // @param switchto - is an integer
    // @param ids      - is an array of ids
    // @param links    - is an array of links

    for (var a=0; a<ids.length; a++)
    {
       if (switchto==a)
       {
           // this is the one that we want to switch on
           var panel = document.getElementById(ids[a]);
           panel.style.visibility       = 'visible';
           panel.style.display          = 'block';
       }
       else
       {
           // hide the others
           var panel = document.getElementById(ids[a]);
           panel.style.visibility       = 'hidden';
           panel.style.display          = 'none';
       }
    }
}

function toggleById(elId)
{
    $('#'+elId).toggle();
}

function rotateTextIn(elId, sources, linkobj, startlinktxt, endlinktxt)
{
   // First element is the Id of the destination tag, sources is the id of the parent tag containing all the <div> tags acting as sources that
   // will rotate one by one. Comparison is done by string so be careful on what you put there...
   // Usage:
   // <div id="comment_1">Text 1</quote>
   // <a href="javascript:rotateTextIn('comment_1','comment_1_sources',this,'More &#187;','&#188; Less');">More &#187;</a>
   // NOTE: More link will appear only on indexes < totalnumberofindexes. Otherwise it will change to Less
   // <span id="comment_1_sources" style="display:none; height:0px;">
   //   <span row="set">Text 1</span>
   //   <span row="set">Text 2</span>
   //   <span row="set">Text 3</span>
   //   <span row="set">... so on....</span>
   // </span>
   // Special Note: IE likes to add a space character if the innerHTML works with other HTML tags within itself...
   // So we need to escape everything, and remove %20 to actually compare stuff properly... FF and Opera do not have that issue

   var obj=document.getElementById(elId);
   var sources=document.getElementById(sources).getElementsByTagName("span");

   var all_texts = new Array();
   var cur_text = obj.innerHTML.replace(/<.*?>|\s|\W|\n|\r|\t/g,"");
   var cur_index = 0;
   // read all the texts and check which one we already have
   for (a=0; a<sources.length; a++)
   {
       if (sources[a].getAttribute('row')=='set')
       {
           var thissource=sources[a].innerHTML.replace(/<.*?>|\s|\W|\n|\r|\t/g,"");
           all_texts[all_texts.length]=sources[a].innerHTML;
           if (cur_text==thissource)
           {
              cur_index=all_texts.length-1;
           }
       }
   }
   var howmany=all_texts.length-1;
   var current= cur_index;

   if (howmany > 0)
   {
      // set the text
      if (howmany > cur_index)
      {
         // index in the middle
         obj.innerHTML = all_texts[cur_index+1];
         current++;
      }
      if (howmany == cur_index)
      {
         // index at the end, so jump to the begining
         obj.innerHTML = all_texts[0];
         current=0;
      }

      // set the link text
      if (howmany > current)
      {
         linkobj.innerHTML=startlinktxt;
      }
      else
      {
         linkobj.innerHTML=endlinktxt;
      }
   }
   // if we do not have any sources, do not do anything
}

// flash functions
function sendEvent(swf,typ,prm)
{
    thisMovie(swf).sendEvent(typ,prm);
};

function getUpdate(typ,pr1,pr2,swf) {};

function thisMovie(swf)
{
   var obj = document.getElementById(swf);
   return obj;
};

function loadFile(swf,obj)
{
    thisMovie(swf).loadFile(obj);
};

function showVid(playlist,thumbnail)
{
    var pObj = {file: playlist, image: thumbnail, width: 313, height: 263, repeat: 'true', shuffle: 'false', showstop: 'false'};
    loadFile('pic1',pObj);

};

function showSoundslide(soundslide,thumbnail)
{
    var pObj = {file: soundslide, image: thumbnail, width: 313, height: 263, repeat: 'true', shuffle: 'false', showstop: 'false'};
    loadFile('pic1',pObj);

};

function createplayer(theFile, go)
{
    var s = new SWFObject("/resources/flash/flashplayer_as3_sm.swf/","pic1","313","268","9");
    so.addParam("allowfullscreen","true");
    so.addVariable("file",theFile);
    so.addVariable("width","313");
    so.addVariable("height","268");
    so.addVariable("shuffle","false");
    so.addVariable("repeat","always");
    so.addVariable("thumbsinplaylist","true");
    if (go) {so.addVariable("autostart","false");}
    so.write("flashPlayer");
}

function playMp3(mp3file,id)
{
    //var thumbnail = '';
    //var pObj = {file: mp3file, image: thumbnail, width:140, height: 20, repeat: 'false', autostart: 'true'};
    //loadFile('mp3',pObj);
    //player.sendEvent("PLAY");
    //setTimeout("thisMovie('mp3player').sendEvent('playitem', 0)", 3000);
    thisMovie(id).sendEvent('playpause','true');
}

// Classified search form validation
function validate_search(aField)
{
    var eField = aField.LOCATION;
    if(!eField)
        return true;
    if(eField.value == '' || eField.value == 'Town, County or Postcode')
    {
        alert("You must fill in the Location field!");
        eField.focus();
        eField.value = '';
        return false;
    }
    return true;
}

function redirect(obj)
{
    var url = obj.options[obj.selectedIndex].value;
    if (url !== '')
    {
        window.location = url;
    }
}

function createGMTDate()
{
   var tdate = new Date();
   var today = new Date(tdate.toGMTString());
   var w = today.getDay();
   var m = today.getMonth();
   var y = today.getFullYear();
   var d = today.getDate();
   var day = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
   var month = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

   // get a textural representation of the month
   m = month[m];
   w = day[w];

   // format a date string
   var newDate = w + ', ' + d + ' ' + m + ' ' + y;

   // write it to the correct id
   $('#time').html(newDate);
}

function startFeaturedJobsScroller()
{
    var featured_jobs_scroller = document.getElementById('scrolling_featured_jobs');

    /* Count all the li tags within and do not initiate the scroller if the number is smaller than 6 jobs */
    var count = $('#scrolling_featured_jobs li').length;
    if ((featured_jobs_scroller != null) && (count > 6))
    {
        var scrolling_featured_jobs = new Scroller(featured_jobs_scroller, 'up', 100);
           scrolling_featured_jobs.run();
    }
}

// jQuery Auto start functions
$(document).ready(function()
{
    commentHandler.init();

    attachClearOnFocus();

    // Supersleight plugin - IE6 png fix
    jQuery.fn.supersleight = function(settings) {
        settings = jQuery.extend({
            imgs: true,
            backgrounds: true,
            shim: 'blank.gif',
            apply_positioning: true
        }, settings);

        return this.each(function(){
            if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
                jQuery(this).find('*').andSelf().each(function(i,obj) {
                    var self = jQuery(obj);
                    // background pngs
                    if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
                        var bg = self.css('background-image');
                        var src = bg.substring(5,bg.length-2);
                        var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
                        var styles = {
                            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
                            'background-image': 'url('+settings.shim+')'
                        };
                        self.css(styles);
                    };
                    // image elements
                    if (settings.imgs && self.is('img[src$=png]')){
                        var styles = {
                            'width': self.width() + 'px',
                            'height': self.height() + 'px',
                            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
                        };
                        self.css(styles).attr('src', settings.shim);
                    };
                    // apply position to 'active' elements
                    if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
                        self.css('position', 'relative');
                    };
                });
            };
        });
    };

	// iosList Plugin
	$.fn.ioslist = function(options) {
		//allow for defaults to be overridden even though we won't talk about it much
		//you can make this work with any set of DOM elements provided you know how to style it right
		var defaults = {
			groupContainer: "dl",
			groupHeader: "dt",
			stationaryHeaderClass: "fakeHeader",
			stationaryHeaderElement: "h2"
		};
		var options = $.extend(defaults,options);
		
		return this.each(function(){
			var $listWrapper;		//wrap everything, holds $fakeHeader in place
			var $fakeHeader;		//fixed header element
			var $listContainer; 	//element ioslist method was called on
			var elems = [];			//array of DOM elements and props, reduces DOM access

			//create and cache necessary elements
			$(this).wrap("<div class='listWrapper'></div>");
			$listContainer = $(this);
			$listWrapper = $(this).parent();
			$listWrapper.prepend("<" + options.stationaryHeaderElement + "/>");
			$fakeHeader = $listWrapper.find(options.stationaryHeaderElement).eq(0);
			$fakeHeader.addClass(options.stationaryHeaderClass);
			
			$listContainer.find(options.groupContainer).each(function (index,elem) {
				var $tmp_list = $listContainer.find(options.groupContainer).eq(index);
				var $tmp_header = $tmp_list.find(options.groupHeader).eq(0);
				var $tmp_listHeight = $tmp_list.height();
				var $tmp_listOffset = $tmp_list.position().top;
				elems.push({"list" : $tmp_list,
							"header" : $tmp_header,
							"listHeight" : $tmp_listHeight,
							"headerText" : $tmp_header.text(),
							"headerHeight" : $tmp_header.outerHeight(),
							"listOffset" : $tmp_listOffset,
							"listBottom" : $tmp_listHeight + $tmp_listOffset});
			});
			
			$fakeHeader.text(elems[0].headerText);

			//bind to the scroll event
			$listContainer.scroll(function() {
				testPosition();
			});
			
			function testPosition() {
				var currentTop = $listContainer.scrollTop();
				var topElement;
				var offscreenElement;
				var topElementBottom;
				var i = 0;
				
				while((elems[i].listOffset - currentTop) <= 0) {
					topElement = elems[i];
					topElementBottom = topElement.listBottom - currentTop;
					if(topElementBottom < -topElement.headerHeight) {
						offscreenElement = topElement;
					}
					i++;
				}
				
				if(topElementBottom < 0 && topElementBottom > -topElement.headerHeight) {
					$fakeHeader.addClass("hidden");
					$listContainer.find('dl').removeClass("animated");
					$(topElement.list).addClass("animated");
				} else {
					$fakeHeader.removeClass("hidden");
					$listContainer.find('dl').removeClass("animated");
				}
				
				$fakeHeader.text(topElement.headerText);

			}
		});
	} // END iosList Plugin

    // Initialize Autocompleters
    $("#Site-search").autocomplete("/search/autoSiteSearch/jQuery/", {minChars: 3, cacheLength: 20});
    $("#LocationjQuery").autocomplete("/resources/location-auto-complete/", {minChars: 3, cacheLength: 20, width: '250px'});
    // $("#LocationjQuery").autocomplete("/homes/completionlistjQuery/", { minChars: 3, cacheLength: 20, width: '250px', delay: 100 });

    // start job scroller
    //var tt = setTimeout("startFeaturedJobsScroller()", 3000);

    // Generic search field clearing on focus
        $.fn.clearform = function() {
            return this.focus(function() {
                if( $(this).val().indexOf("e.g.") > -1 ) { // previously if( this.value == this.defaultValue ) {
                    this.value = "";
                }
            }); /*.blur(function() { //reinstates default value on blur
                if( !this.value.length ) {
                    this.value = this.defaultValue;
                }
            }); */
        };
    // Clear form inputs for user account pages
    $("#userAccount input:text").clearform();

    // Search results 'relevant sections' toggle
    if ($('.searchRelSecListMore').length > 0)
    {
        // $('.searchRelSecListMore').hide();
        // $('.searchRelSecList').append('<li class="searchRelShowHide">Show more sections</li>');
        $('.searchRelShowHide').toggle(
            function() {
                $('.searchRelSecListMore').slideToggle();
                $(this).text('Show fewer sections');
            },
            function() {
                $('.searchRelSecListMore').slideToggle();
                $(this).text('Show more sections');
            }
        );
    }

    // Share links on article pages (excluding families)
    $('.articleShareBox').addClass('popBox');
    var shareBoxHtml = $('.articleShareBox').removeAttr('id').wrap('<div></div>').parent().html();
    $('.articleShareBox').parent().remove();
    $('.articleUtilShare a').removeAttr('href').click(
        function() {
            var checkBoxExists = $(this).next('div').html();
            if (!checkBoxExists) {
                $(this).parent().append(shareBoxHtml).find('div').toggle();
                toggleShare();
            } else {
                $(this).next('div').toggle();
                toggleShare();
            }
        }
    );
    // ShareBox hide
    function toggleShare() {
        $('.articleShareBox span').click(function() {
            $(this).parent().hide();
        });
    };

    /* Share links on family pages - why do we need to have this separated?
    $('.shareBox').addClass('popBox');
    var shareBoxHtmlFamily = $('.shareBox').removeAttr('id').wrap('<div></div>').parent().html();
    $('.shareBox').parent().remove();
    $('.noticeUtilShare a').removeAttr('href').click(
        function() {
            var checkBoxExists = $(this).next('div').html();
            if (!checkBoxExists) {
                $(this).parent().append(shareBoxHtmlFamily);
                toggleFamiliesShare();
            } else {
                $(this).next('div').show();
                toggleFamiliesShare();
            }
        }
    );

    // ShareBox hide
    function toggleFamiliesShare() {
        $('.shareBox span').click(function() {
            $(this).parent().hide();
        });
    };
    */

    // JOB SECTOR TOGGLE
    $("#myJobsSearch .sectorToggle").show();
    $("#myJobsSearch .sectorToggle").click(function() {
         if (!$(this).is(".allSelected")) {
             $(this).next().children().children("input").attr("checked", "checked");
             $(this).addClass("allSelected").html("Deselect all &#187;");
         } else {
             $(this).next().children().children("input").removeAttr("checked");
             $(this).removeClass("allSelected").html("Select all &#187;");
         }
    });

    // Families (old NetMums) pages - FaceBox initialize
    if ($('a[rel*=facebox]').length > 0)
    {
       $('a[rel*=facebox]').facebox();
    }

    // HOMES/JOB SEARCH FUNCTIONS
    $("#myHomesSearch .searchOptions .sale").click(function() {
        $(this).addClass("on");
        $("#myHomesSearch .searchOptions .rent").removeClass("on");
        $("#myHomesSearch #homeSale").css({"display":"block"});
        $("#myHomesSearch #homeRent").css({"display":"none"});
    });

    $(".searchOptions .rent").click(function() {
        $(this).addClass("on");
        $("#myHomesSearch .searchOptions .sale").removeClass("on");
        $("#myHomesSearch #homeRent").css({"display":"block"});
        $("#myHomesSearch #homeSale").css({"display":"none"});
    });

    $("#_eventId_continue").click(function()
    {
        if($("#terms:checked").length == 1)
        {
            $("#cvUploadStep1").submit();
        }
        else
        {
            $("#unticked").removeClass('none');
        }
    });


    $('#salaryFrequencyId').change(function(){
        var baseSalary = 0;
        var diffSalary = 0;

        if($(this).val() == 1)
        {
            baseSalary = 5;
            diffSalary = 1;
        }
        if($(this).val() == 2)
        {
            baseSalary = 25;
            diffSalary = 5;
        }
        if($(this).val() == 3)
        {
            baseSalary = 50;
            diffSalary = 50;
        }
        if($(this).val() == 4)
        {
            baseSalary = 250;
            diffSalary = 250;
        }
        if($(this).val() == 5)
        {
            baseSalary = 5000;
            diffSalary = 5000;
        }
        if(baseSalary > 0)
        {
            var htmlReplacement = '<option value="">Please select a salary</option>';
            for(var i = 0; i < 20; i++)
            {
                var salary = baseSalary + (i*diffSalary);
                formatted = ''+salary;
                if(salary > 999)
                {
                    var under = salary % 1000;
                    var over  = Math.floor(salary/1000);
                    under = ''+under;
                    while(under.length < 3)
                    {
                        under = '0'+under;
                    }

                    formatted = over+','+under;
                }
                htmlReplacement = htmlReplacement+'<option value="'+salary+'">&pound;'+formatted+'</option>';
                if(i > 4)
                {
                    i++;
                }
            }
            $('#desiredSalaryMinimum, #desiredSalaryMaximum').html(htmlReplacement);
        }
    });

	// Generic form field focus highlight
	function focusHighlight() {
		$("input[type=text],input[type=password],input[type=file],textarea,select,.genericRadio input[type=checkbox]").focus(function() {
			$(this).parent().addClass("formFocus");
		});
		$("input[type=text],input[type=password],input[type=file],textarea,select,.genericRadio input[type=checkbox]").blur(function() {
			$(this).parent().removeClass("formFocus");
		});

		$("input[type=radio]").focus(function() {
			$(this).parent().parent().addClass("formFocus");
		});
		$("input[type=radio]").blur(function() {
			$(this).parent().parent().removeClass("formFocus");
		});
	}

	// 'Send your news' form highlight current field
	if ($(".sendYourNewsForm").length > 0 ) focusHighlight();


	// 'Send your news' image increment
	if ($('.sendYourNewsForm').length > 0) {
		$('.sendYourNewsPhotos ul li:gt(1)').hide();
		$('.sendYourNewsPhotos').append('<p class="sendYourNewsAdd"><a href="#sendYourNews">Add another</a></p>');

		$('.sendYourNewsAdd a').click(function() {
			$('.sendYourNewsPhotos ul li:not(:visible):lt(2)').slideDown();
			if ($('.sendYourNewsPhotos ul li:not(:visible)').length == 0) $('.sendYourNewsAdd').fadeOut('slow', function() {$(this).remove();});
			return false;
		});
	}

	// 'Send your news' validation
	if ($('.sendYourNewsForm').length > 0) {
		if ($('.validateError').length == 0) $('.sendYourNewsForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

		$('.sendYourNewsForm').validate({
			ignoreTitle: true,
			errorContainer: ".validateError",
			errorLabelContainer: ".validateError ul",
			wrapper: "li",
			errorClass: "fieldInvalid",
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.removeClass(errorClass);
			},

			rules: {
				name: {
					required: false,
					minlength: 2
				},
				email: {
					required: false,
					email: true
				},
				telephone: {
					required: false,
					phoneUK: true
				},
				headline: {
					required: true,
					minlength: 5
				},
				body: {
					required: true,
					minlength: 20
				},
				image1: {
					required: false,
					accept: "png|gif|jpg|jpeg"
				},
				caption1: {
					required: false,
					minlength: 2
				},
				image2: {
					required: false,
					accept: "png|gif|jpg|jpeg"
				},
				caption2: {
					required: false,
					minlength: 2
				},
				image3: {
					required: false,
					accept: "png|gif|jpg|jpeg"
				},
				caption3: {
					required: false,
					minlength: 2
				},
				image4: {
					required: false,
					accept: "png|gif|jpg|jpeg"
				},
				caption4: {
					required: false,
					minlength: 2
				},
				recaptcha_response_field: {
					required: true
				}

            },

            messages: {
                name: {
                    required: "Please specify your <strong>name</strong>",
                    minlength: jQuery.format("Your <strong>name</strong> should have at least {0} characters")
                },
                email: {
                    required: "Please specify your <strong>email address</strong>",
                    email: "Your <strong>email address</strong> must be in the format name@domain.com"
                },
                telephone: {
                    required: "Please specify a <strong>telephone</strong> or mobile number",
                    phoneUK: "Please enter a valid UK <strong>telephone</strong> number"
                },
                headline: {
                    required: "Please specify a <strong>title or headline</strong> for your story",
                    minlength: jQuery.format("Please enter a meaningful <strong>title or headline</strong> for your story")
                },
                body: {
                    required: "Don't forget to include your <strong>story</strong>",
                    minlength: jQuery.format("Your <strong>story</strong> should probably be a little longer")
                },
                image1: {
                    accept: "Your <strong>photo 1</strong> should be in jpg, gif or png format"
                },
                caption1: {
                    required: "Please specify a <strong>caption</strong> for photo 1",
                    minlength: jQuery.format("The <strong>caption</strong> for photo 1 should have at least {0} characters")
                },
                image2: {
                    accept: "Your <strong>photo 2</strong> should be in jpg, gif or png format"
                },
                caption2: {
                    required: "Please specify a <strong>caption</strong> for photo 2",
                    minlength: jQuery.format("The <strong>caption</strong> for photo 2 should have at least {0} characters")
                },
                image3: {
                    accept: "Your <strong>photo 3</strong> should be in jpg, gif or png format"
                },
                caption3: {
                    required: "Please specify a <strong>caption</strong> for photo 3",
                    minlength: jQuery.format("The <strong>caption</strong> for photo 3 should have at least {0} characters")
                },
                image4: {
                    accept: "Your <strong>photo 4</strong> should be in jpg, gif or png format"
                },
                caption4: {
                    required: "Please specify a <strong>caption</strong> for photo 4",
                    minlength: jQuery.format("The <strong>caption</strong> for photo 4 should have at least {0} characters")
                },
                recaptcha_response_field: {
                    required: "Please enter the security words"
                }
            }

        });

    }

    // Register form highlight current field
    if ($(".regForm").length > 0) focusHighlight();
    if ($(".regActivate").length > 0) focusHighlight();
    if ($(".logForm").length > 0) focusHighlight();
    if ($(".accForm").length > 0) focusHighlight();
    if ($(".accFormNewsletters").length > 0) focusHighlight();

    // Register validation - Step 1
    if ($('.regStep1 .regForm').length > 0) {
        if ($('.validateError').length == 0) $('.regForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

        $('.regForm').validate({
            ignoreTitle: true,
            errorContainer: ".validateError",
            errorLabelContainer: ".validateError ul",
            wrapper: "li",
            errorClass: "fieldInvalid",
            highlight: function(element, errorClass) {
                $(element).addClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .removeClass(errorClass);
            },

            rules: {
                regemail: {
                    required: true,
                    email: true
                },
                regpassword: {
                    required: true,
                    minlength: 6
                },
                regpasswordconfirm: {
                    required: true,
                    minlength: 6,
                    equalTo: "#regpassword"
                }
            },

            messages: {
                regemail: {
                    required: "Please specify your <strong>email address</strong>.",
                    email: "Your <strong>email address</strong> must be in the format name@domain.com."
                },
                regpassword: {
                    required: "Please specify a <strong>password</strong>.",
                    minlength: jQuery.format("Your <strong>password</strong> must contain at least {0} characters.")
                },
                regpasswordconfirm: {
                    required: "Please confirm your <strong>password</strong>.",
                    minlength: jQuery.format("Your <strong>password</strong> must contain at least {0} characters."),
                    equalTo: "The <strong>confirm password</strong> field does not match the 'password' field."
                }
            }

        });
    } // End step 1 val

    // Register validation - Step 2
    if ($('.regStep2 .regForm').length > 0) {
        if ($('.validateError').length == 0) $('.regForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

        $('.regForm').validate({
            ignoreTitle: true,
            errorContainer: ".validateError",
            errorLabelContainer: ".validateError ul",
            wrapper: "li",
            errorClass: "fieldInvalid",
            highlight: function(element, errorClass) {
                $(element).addClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .removeClass(errorClass);
            },

            rules: {
                regusername: {
                    required: true,
                    minlength: 6
                },
                regtitle: {
                    required: true
                },
                regfirstname: {
                    required: true,
                    minlength: 2
                },
                reglastname: {
                    required: true,
                    minlength: 2
                }
            },

            messages: {
                regusername: {
                    required: "Please specify a <strong>username</strong>.",
                    minlength: jQuery.format("Your <strong>username</strong> must contain at least {0} characters.")
                },
                regtitle: {
                    required: "Please select a <strong>title</strong>."
                },
                regfirstname: {
                    required: "Please specify your <strong>first name</strong>.",
                    minlength: jQuery.format("Your <strong>first name</strong> must contain at least {0} characters.")
                },
                reglastname: {
                    required: "Please specify your <strong>last name</strong>.",
                    minlength: jQuery.format("Your <strong>last name</strong> must contain at least {0} characters.")
                }
            }

        });
    } // End step 2 val

    // Activate validation
    if ($('.regStep4 .regActivate').length > 0) {
        if ($('.validateError').length == 0) $('.regActivate').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

        $('.regActivate').validate({
            ignoreTitle: true,
            errorContainer: ".validateError",
            errorLabelContainer: ".validateError ul",
            wrapper: "li",
            errorClass: "fieldInvalid",
            highlight: function(element, errorClass) {
                $(element).addClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .removeClass(errorClass);
            },

            rules: {
                email: {
                    required: true,
                    email: true
                },
                passcode: {
                    required: true,
                    minlength: 32
                }
            },

            messages: {
                email: {
                    required: "Please specify your <strong>email address</strong>.",
                    email: "Your <strong>email address</strong> must be in the format name@domain.com."
                },
                passcode: {
                    required: "Please enter your <strong>passcode</strong>.",
                    minlength: jQuery.format("Your <strong>passcode</strong> should be {0} characters long. Please ensure you have copied and pasted the full passcode.")
                }
            }

        });
    } // End activate val

    // Log in validation
    if ($('.login .logForm').length > 0) {
        if ($('.validateError').length == 0) $('.logForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

        $('.logForm').validate({
            ignoreTitle: true,
            errorContainer: ".validateError",
            errorLabelContainer: ".validateError ul",
            wrapper: "li",
            errorClass: "fieldInvalid",
            highlight: function(element, errorClass) {
                $(element).addClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .removeClass(errorClass);
            },

            rules: {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true,
                    minlength: 4
                }
            },

            messages: {
                email: {
                    required: "Please specify your <strong>email address</strong>.",
                    email: "Your <strong>email address</strong> must be in the format name@domain.com."
                },
                password: {
                    required: "Please specify a <strong>password</strong>.",
                    minlength: jQuery.format("Your <strong>password</strong> must contain at least {0} characters.")
                }
            }

        });
    } // End log in val

    // MY ACCOUNT HOME - Update details toggle
    if ($('.accHome .accForm').length > 0) {
        $('.accHome fieldset').addClass('accJsView');
        $('input,select', '.accHome > form').attr('disabled','disabled');
        var selectVal = $('.accHome select').val().substr(0,1).toUpperCase()+$('.accHome select').val().substr(1).toLowerCase();
        $('.accHome select').hide().before('<span class="select">' + selectVal + '</span>');

        $('a.genericButton').click(function() {
            $(this).parent().removeClass('accJsView');
            $(this).parent().find('input,select').not('#username').removeAttr('disabled');
            if ($(this).parent().find('select').length > 0) {
                var selectVal = $('select').val();
                $('span.select').hide(0);
                $('select').show();
            }
            if ($(this).attr('href').substr(0, 22) == "http://m.facebook.com/")
            {
                //FB.logout(function () { document.location = '/my/account/log-out/'});
                return true;
            }
            else if ($(this).attr('href') == "/my/account/log-out/")
            {
                return true;
            }
            return false;
        });
    }

    // MY ACCOUNT HOME validation
    if ($('.accHome .accForm').length > 0) {
        if ($('.validateError').length == 0) $('.accForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

        $('.genericForm').validate({
            ignoreTitle: true,
            errorContainer: ".validateError",
            errorLabelContainer: ".validateError ul",
            wrapper: "li",
            errorClass: "fieldInvalid",
            highlight: function(element, errorClass) {
                $(element).addClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .removeClass(errorClass);
            },

            rules: {
                email: {
                    required: true,
                    email: true
                },
                registerusername: {
                    required: true,
                    minlength: 6
                },
                registertitle: {
                    required: true
                },
                realname: {
                    required: true,
                    minlength: 2
                }
            },

            messages: {
                email: {
                    required: "Please specify your <strong>email address</strong>.",
                    email: "Your <strong>email address</strong> must be in the format name@domain.com."
                },
                registerusername: {
                    required: "Please specify a <strong>username</strong>.",
                    minlength: jQuery.format("Your <strong>username</strong> must contain at least {0} characters.")
                },
                registertitle: {
                    required: "Please select a <strong>title</strong>."
                },
                realname: {
                    required: "Please specify your <strong>real name</strong>.",
                    minlength: jQuery.format("Your <strong>real name</strong> must contain at least {0} characters.")
                }
            }

        });
    } // End MY ACCOUNT home val

    // Comment Log in validation
    if ($(".commentLogUs form").length > 0) focusHighlight();
    if ($('.commentLogUs form').length > 0) {
        if ($('.validateError').length == 0) $('.commentLogUs form').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');

        $('.commentLogUs form').validate({
            ignoreTitle: true,
            errorContainer: ".validateError",
            errorLabelContainer: ".validateError ul",
            wrapper: "li",
            errorClass: "fieldInvalid",
            highlight: function(element, errorClass) {
                $(element).addClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").parent()
                        .removeClass(errorClass);
            },

            rules: {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true,
                    minlength: 4
                }
            },

            messages: {
                email: {
                    required: "Please specify your <strong>email address</strong>.",
                    email: "Your <strong>email address</strong> must be in the format name@domain.com."
                },
                password: {
                    required: "Please specify a <strong>password</strong>.",
                    minlength: jQuery.format("Your <strong>password</strong> must contain at least {0} characters.")
                }
            }

        });
    } // End Comment log in val

    // Traffic cameras
    if ($('a[rel*=trafficslideshow]').length > 0) {
       $('a[rel*=trafficslideshow]').colorbox({slideshow:true, width:"600px", opacity:"0.1"});
    }

    //Weather IE6 PNGs fix
    $('.weatherIcon').supersleight({shim: '/resources/static/standard/images/blank.gif'});
    $('#weather .btnWeatherNext, #weather .btnWeatherPrev').supersleight({shim: '/resources/static/standard/images/blank.gif'});

    //Weather carousel
    if ($('#weather .carousel').length > 0) {
            $('#weather .carousel').jcarousel({
                buttonNextHTML: '<div class="btnWeatherNext"></div>',
                buttonPrevHTML: '<div class="btnWeatherPrev"></div>',
                itemFallbackDimension: '310',
                scroll: 1
            });
        }

    //Weather maps
    if ($('#weather .weatherMaps').length > 0) {
            $('#weather .weatherMaps a:first').parent().addClass('weatherMapOn');

            $('#weather .weatherMaps a').click(function() {
                $('#weather .weatherMaps li').removeClass('weatherMapOn');
                $(this).parent().addClass('weatherMapOn');
                return false;
            });
        }
    //TRAFFIC & TRAVEL//
    if ($('.trafficIncidents').length > 0) {

        // add a submit handler to the form
        $('#traffic_form').submit(submitTraffic);

        // set
        burl = document.location.pathname.toString();

        matches = burl.match(/(public_transport|traffic|roadworks|public_engineering).in/);
        if (matches != null)
        {
            match = matches[1];

            $('#traffic_type').val(match).attr("selected", "selected");
        }

        // get the query string for the sort and set the correct form
        sortVal = qs.get('sort');
        if (sortVal !== null)
        {
            $('#traffic_order').val(sortVal).attr("selected", "selected");
        }


        if ($('.trafficCams').length > 0) {
            $('#traffic .trafficCams p span').css({opacity: 0.6});
        }

        if (jQuery.support.opacity) {
			$('.trafficIncidents .trafficShare, .trafficIncidents .trafficViewMap').css({opacity: 0});
			$('.trafficIncidents .trafficViewMore').css({opacity: 0.8});

			$('.trafficIncidents li').hover(
				function () {
					$('.trafficShare, .trafficViewMap',this).stop(false, true).animate({opacity: 1}, 500 );
					$('.trafficViewMore',this).stop(false, true).animate({opacity: 1}, 500 );
				},
				function () {
				   $('.trafficShare, .trafficViewMap',this).stop(false, true).animate({opacity: 0}, 300 );
				   $('.trafficViewMore',this).stop(false, true).animate({opacity: 0.8}, 300 );
				}
			);
		}

        $('.trafficCams ul li a').click(
            function() {
                var currentPic = $(this).attr('href');
                var currentCaption = $('img',this).attr('alt');
                $('.trafficCamsMain').attr('src', currentPic);
                $('.trafficCams p span').text(currentCaption);
                return false;
            }
        );

        //TRAFFIC & TRAVEL GOOGLE MAPS//
        var trafficMap = {
            bounds: null,
            map: null
        }

        trafficMap.init = function(latLng, zoom) {
            var myOptions = {
                zoom:zoom,
                center: latLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            this.map = new google.maps.Map(document.getElementById("trafficMap"), myOptions);
            this.bounds = new google.maps.LatLngBounds();
            //var trafficLayer = new google.maps.TrafficLayer();
            //trafficLayer.setMap(trafficMap.map);
        }

        var infoWindow;
        var mapY = $('#traffic').offset().top;
        trafficMap.placeMarkers = function() {

            $('.trafficIncidents .trafficList > li').each(function(){
                var incidentID    = (this.id).split("-");
                var incident = incidentID[1];
                var type = $('.trafficIcons span', this).last().attr('class');
                var severityID = $(this).attr('class').split(" ");
                var severity = severityID[0];

                if (typeof type == 'undefined')
                {
                    return;
                }

                var icon = '/resources/static/standard/images/traffic-marker-' + type + '.png/';
                var lat = $(this).find('.lat').text();
                var lng = $(this).find('.lng').text();
                var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
                // extend the bounds to include the new point
                trafficMap.bounds.extend(point);
                // add the marker itself
                var marker = new google.maps.Marker({
                position: point,
                map: trafficMap.map,
                icon: icon
                });
                // create the tooltip and its text
                //infoWindow = new google.maps.InfoWindow();
                infoWindow = new InfoBubble({
                  content: html,
                  shadowStyle: 1,
                  padding: 0,
                  minWidth: 300,
                  maxWidth: 300,
                  minHeight: 100,
                  maxHeight: 200,
                  backgroundColor: '#FFF',
                  borderRadius: 5,
                  arrowSize: 10,
                  borderWidth: 4,
                  borderColor: '#666',
                  disableAutoPan: false,
                  hideCloseButton: true,
                  arrowPosition: 50,
                  backgroundClassName: 'trafficBubble clearfix',
                  arrowStyle: 0
                });

                var html = $(this).clone().find('h4').addClass(severity).parent();
                html.find('.trafficShare').remove();//removeAttr('style').parent();
                if ($('.trafficViewMore').length > 0) {
                    html = html.find('.trafficViewMore').removeAttr('style').remove().appendTo(html).parent().html();
                } else {
                    html = html.html();
                }

                // add a listener to open the tooltip when a user clicks on one of the markers
                google.maps.event.addListener(marker, 'click', function() {
                    infoWindow.close();
                    infoWindow.setContent(html);
                    infoWindow.open(trafficMap.map, marker);
                });
                google.maps.event.addListener(trafficMap.map, 'click', function() {
                    infoWindow.close();
                });

                $('.trafficViewMap a',this).click(function(){
                    $(this).parents("html:not(:animated),body:not(:animated)").animate({scrollTop: mapY}, 1000);
                    infoWindow.close();
                    infoWindow.setContent(html);
                    infoWindow.open(trafficMap.map, marker);
                    return false;
                });

                // Fit the map around the markers we added:
                if ($('#defaultMapBounds').html() !== 'false')
                {
                    trafficMap.map.fitBounds(trafficMap.bounds);
                }

            });
        }

        //var myLatLng = new google.maps.LatLng(53.717787, -2.674731);
        var myLatLng = new google.maps.LatLng(parseFloat($('#defaultCentreLat').html()),parseFloat($('#defaultCentreLon').html()));
        var zoom = parseInt($('#defaultZoomLevel').html());
        var mapType = $('#defaultMapType').html();
        if (mapType === 'Sat')
        {
            mapType = google.maps.MapTypeId.SATELLITE;
        }
        else
        {
            mapType = google.maps.MapTypeId.ROADMAP;
        }
        trafficMap.init(myLatLng, zoom);
        trafficMap.placeMarkers();

    }//END TRAFFIC & TRAVEL//

	//EVENTS LANDING PAGE //
	if ($("#eventsList1").length > 0) {
		// Apply ioslist plugin to events landing page panel
		$("#eventsList1").ioslist({
			stationaryHeaderElement: "h3"
		});
		
		// Get current time
		var time = new Date();
		var hours = time.getUTCHours();
		if (hours < 10) hours = "0" + hours;
		var minutes = time.getUTCMinutes();
		if (minutes < 10) minutes = "0" + minutes;
		var userTime = hours + '' + minutes;
		// Build array of times appearing in the panel
		var elems = $("#eventsList1 dt").toArray();
		// Extract time from ids for this array
		var idArr = [];
		$.each(elems, function() {
				idArr.push(this.id);
		});
		// Check current time against available times in the array 
		$.each(idArr, function(i) {
			var id = idArr[i].substring(4); // remove 'time' from id
			if (id >= userTime) {
				// Position next available event at the top of the list
				var elemY = $(elems[i]).offset().top - $(elems[i]).parents('div').offset().top;
				$(elems[i]).parents('div').scrollTop(elemY);
				return false;
			}
			$(elems[i]).parent().addClass('eventStarted');
			i++;
		});
	}
	//END EVENTS LANDING PAGE //
	
    //HOMES SERVICE//
    $('.soldHousePriceSubmit').click(function(event){
        event.preventDefault();
        $('#streetname').attr('value',$('#streetname').attr('value').replace("'", "_"));
        $('.soldHousePriceSearch').submit();
    });
    //END HOMES SERVICE//

    //OpenId quick logins
    $('#openIdGoogle').click(function(){
        window.open('/my/openId/?type=google', '_blank', 'height=450,width=550px,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no');
		return false;
    });
    $('#openIdYahoo').click(function(){
        window.open('/my/openId/?type=yahoo', '_blank', 'height=450,width=550px,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no');
		return false;
    });
    $('#openIdTwitter').click(function(){
        window.open('/my/openId/?type=twitter', '_blank', 'height=450,width=550px,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no');
		return false;
    });
	
	// ARTICLE GALLERY //
	if($('.articleGallery').length > 0) {
		$('.articleGallery li a').each(function(){
			var src = $(this).attr('href');
			var image = $('<img />').attr('src', src);
		});
		
		$('.articleGallery li a').click(function() {
			var src = $(this).attr('href');
			var buy = $(this).attr('rel');
			var caption = $('img',this).attr('alt');
			$('.articleGallery li').removeClass('current');
			$(this).parent().addClass('current');
			$('.articleGallery .articlePhoto img').attr('src',src);
			if (buy == "") {
				$('.articleGallery .articlePhoto span').text(caption);
			} else {
				$('.articleGallery .articlePhoto span').html(caption + '<a href="' + buy + '" class="articlePhotoBuy">Buy this photo &#187;</a>');
			}
			return false;
		});
	}
	
	// FLOATER //
	if($('.skyFloat').length > 0) {
		setTimeout(function() { 
            // sky float has been removed as their is no advert
	        if($('.skyFloat').length == 0)
            {
                return;
            }
		
			var top = $('.skyFloat').offset().top - parseFloat($('.skyFloat').css('marginTop').replace(/auto/, 0));
			var bottom = $('.lowerAds').offset().top;
			
			$(window).scroll(function (event) {
				var y = $(this).scrollTop();
				if (y >= top) {
					$('.skyFloat').addClass('fixed');
					if (y+600 >= bottom) {
						var foot = bottom - 610;
						$('.skyFloat').css({'top' : foot, 'position' : 'absolute'});
					} else {
						$('.skyFloat').removeAttr('style');
					}
				} else {
					$('.skyFloat').removeClass('fixed');
				}
			});
		
		}, 10000);
	}
	
	/**
	* jQuery Cookie plugin
	*
	* Copyright (c) 2010 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
	*
	*/
	jQuery.cookie = function (key, value, options) {

		// key and at least value given, set cookie...
		if (arguments.length > 1 && String(value) !== "[object Object]") {
			options = jQuery.extend({}, options);

			if (value === null || value === undefined) {
				options.expires = -1;
			}

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = String(value);

			return (document.cookie = [
				encodeURIComponent(key), '=',
				options.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
			].join(''));
		}

		// key and possibly options given, get cookie...
		options = value || {};
		var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
		return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
	};
	
	// COMMENTS scoring & sorting //
	if($('.comment').length > 0) {
		$('#commentSort').change(function(){
			$('.commentSort').submit();
		});

		
		if($.cookie('commentPlus') != null) {
			var cookieVal = $.cookie('commentPlus');
			//console.log(cookieVal);
			var cookieArr = cookieVal.split(',');
			//console.log(cookieArr);
			if(cookieVal != '') {
				$.each(cookieArr, function(i) {
					$('#' + cookieArr[i] + ' .commentLike li:not(:first-child)').remove();
					$('#' + cookieArr[i] + ' .commentLike').append('<li class="commentScored">You voted <span class="commentScoredPlus">+1</span></li>');
				});
			}

		} else {
			$.cookie('commentPlus', '', { expires: 7 });
		}
		
		if($.cookie('commentMinus') != null) {
			var cookieVal = $.cookie('commentMinus');
			//console.log(cookieVal);
			var cookieArr = cookieVal.split(',');
			//console.log(cookieArr);
			if(cookieVal != '') {
				$.each(cookieArr, function(i) {
					$('#' + cookieArr[i] + ' .commentLike li:not(:first-child)').remove();
					$('#' + cookieArr[i] + ' .commentLike').append('<li class="commentScored">You voted <span class="commentScoredMinus">-1</span></li>');
				});
			}
		} else {
			$.cookie('commentMinus', '', { expires: 7 });
		}
		
		function scoreCookie(el, val) {
			var postID = el.parents('div[id*="comment_"]').attr('id');
			console.log(postID);
			var cookieVal = $.cookie('comment' + val);
			if(cookieVal != '') {
				cookieVal = cookieVal + ',' + postID;
			} else {
				cookieVal = postID;
			}
			$.cookie('comment' + val, cookieVal, { expires: 7 });
			var scoreVal = parseInt(el.siblings('[class*="commentScore"]').children('span').text());
			
			if (val == 'Plus') { scoreVal = scoreVal + 1; } else { scoreVal = scoreVal - 1; };
			if (scoreVal >= 0) { 
				el.siblings('[class*="commentScore"]').removeClass().addClass('commentScorePlus');
			} else {
				el.siblings('[class*="commentScore"]').removeClass().addClass('commentScoreMinus');
			};
			el.siblings('[class*="commentScore"]').animate({opacity: 0}, 300 ).animate({opacity: 1}, 300 ).children('span').text(scoreVal);
			el.siblings('[class*="commentThumbs"]').remove();
			el.replaceWith('<li class="commentScored">You voted <span class="commentScored' + val + '">+1</span></li>');
		}
		
		$('.commentThumbsUp').click(function(){		
			$.ajax({
				type: "POST",
				url: theurl, //DEV
				success: function() {
					var el = $(this);
					scoreCookie(el, 'Plus');
				}
			})
			return false;
		});
		
		$('.commentThumbsDown').click(function(){
			$.ajax({
				type: "POST",
				url: theurl, //DEV
				success: function() {
					var el = $(this);
					scoreCookie(el, 'Minus');
				}
			})
			return false;
		});
	
	}//END COMMENTS JS
	

}); //END jQuery

// handle the traffic redirects
function submitTraffic()
{
    url = document.location.pathname.toString();

    prefix = $('#traffic_type').val()+'.in';

    options = ['traffic.in','public_transport.in','roadworks.in','traffic_and_travel.in','public_engineering.in'];

    for (i in options)
    {
        url = url.replace(options[i], prefix);
    }

    qString = '?sort='+$('#traffic_order').val();
    document.location = url+qString;

    return false;
}


/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
    if (!document.getElementById) {return;}
    this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
    this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
    this.params = new Object();
    this.variables = new Object();
    this.attributes = new Array();
    if(swf) {this.setAttribute('swf', swf);}
    if(id) {this.setAttribute('id', id);}
    if(w) {this.setAttribute('width', w);}
    if(h) {this.setAttribute('height', h);}
    if(ver) {this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split(".")));}
    this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
    if (!window.opera && document.all && this.installedVer.major > 7) {
        // only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
        deconcept.SWFObject.doPrepUnload = true;
    }
    if(c) {this.addParam('bgcolor', c);}
    var q = quality ? quality : 'high';
    this.addParam('quality', q);
    this.setAttribute('useExpressInstall', false);
    this.setAttribute('doExpressInstall', false);
    var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
    this.setAttribute('xiRedirectUrl', xir);
    this.setAttribute('redirectUrl', '');
    if(redirectUrl) {this.setAttribute('redirectUrl', redirectUrl);}
}
deconcept.SWFObject.prototype = {
    useExpressInstall: function(path) {
        this.xiSWFPath = !path ? "expressinstall.swf" : path;
        this.setAttribute('useExpressInstall', true);
    },
    setAttribute: function(name, value){
        this.attributes[name] = value;
    },
    getAttribute: function(name){
        return this.attributes[name];
    },
    addParam: function(name, value){
        this.params[name] = value;
    },
    getParams: function(){
        return this.params;
    },
    addVariable: function(name, value){
        this.variables[name] = value;
    },
    getVariable: function(name){
        return this.variables[name];
    },
    getVariables: function(){
        return this.variables;
    },
    getVariablePairs: function(){
        var variablePairs = new Array();
        var key;
        var variables = this.getVariables();
        for(key in variables){
            variablePairs[variablePairs.length] = key +"="+ variables[key];
        }
        return variablePairs;
    },
    getSWFHTML: function() {
        var swfNode = "";
        if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
            if (this.getAttribute("doExpressInstall")) {
                this.addVariable("MMplayerType", "PlugIn");
                this.setAttribute('swf', this.xiSWFPath);
            }
            swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'"';
            swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
            var params = this.getParams();
             for(var key in params){swfNode += [key] +'="'+ params[key] +'" ';}
            var pairs = this.getVariablePairs().join("&");
             if (pairs.length > 0){swfNode += 'flashvars="'+ pairs +'"';}
            swfNode += '/>';
        } else { // PC IE
            if (this.getAttribute("doExpressInstall")) {
                this.addVariable("MMplayerType", "ActiveX");
                this.setAttribute('swf', this.xiSWFPath);
            }
            swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
            swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
            var params = this.getParams();
            for(var key in params) {
             swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
            }
            var pairs = this.getVariablePairs().join("&");
            if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
            swfNode += "</object>";
        }
        return swfNode;
    },
    write: function(elementId){
        if(this.getAttribute('useExpressInstall')) {
            // check to see if we need to do an express install
            var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
            if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
                this.setAttribute('doExpressInstall', true);
                this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
                document.title = document.title.slice(0, 47) + " - Flash Player Installation";
                this.addVariable("MMdoctitle", document.title);
            }
        }
        if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
            var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
            n.innerHTML = this.getSWFHTML();
            return true;
        }else{
            if(this.getAttribute('redirectUrl') != "") {
                document.location.replace(this.getAttribute('redirectUrl'));
            }
        }
        return false;
    }
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
    var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
    if(navigator.plugins && navigator.mimeTypes.length){
        var x = navigator.plugins["Shockwave Flash"];
        if(x && x.description) {
            PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
        }
    }else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
        var axo = 1;
        var counter = 3;
        while(axo) {
            try {
                counter++;
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
//              document.write("player v: "+ counter);
                PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
            } catch (e) {
                axo = null;
            }
        }
    } else { // Win IE (non mobile)
        // do minor version lookup in IE, but avoid fp6 crashing issues
        // see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
        try{
            var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        }catch(e){
            try {
                var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
                axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
            } catch(e) {
                if (PlayerVersion.major == 6) {
                    return PlayerVersion;
                }
            }
            try {
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            } catch(e) {}
        }
        if (axo != null) {
            PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
        }
    }
    return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
    this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
    this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
    this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
    if(this.major < fv.major) return false;
    if(this.major > fv.major) return true;
    if(this.minor < fv.minor) return false;
    if(this.minor > fv.minor) return true;
    if(this.rev < fv.rev) return false;
    return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
    getRequestParameter: function(param) {
        var q = document.location.search || document.location.hash;
        if (param == null) {return q;}
        if(q) {
            var pairs = q.substring(1).split("&");
            for (var i=0; i < pairs.length; i++) {
                if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
                    return pairs[i].substring((pairs[i].indexOf("=")+1));
                }
            }
        }
        return "";
    }
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
    var objects = document.getElementsByTagName("OBJECT");
    for (var i = objects.length - 1; i >= 0; i--) {
        objects[i].style.display = 'none';
        for (var x in objects[i]) {
            if (typeof objects[i][x] == 'function') {
                objects[i][x] = function(){};
            }
        }
    }
}
// fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
if (deconcept.SWFObject.doPrepUnload) {
    if (!deconcept.unloadSet) {
        deconcept.SWFObjectUtil.prepUnload = function() {
            __flash_unloadHandler = function(){};
            __flash_savedUnloadHandler = function(){};
            window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
        }
        window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
        deconcept.unloadSet = true;
    }
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) {document.getElementById = function(id) {return document.all[id];}}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;


/* Relevant sections of this site - search page, unfolding more results bit */
function expandContract(id)
{
    if ($('#'+id).is(':hidden'))
    {
        $('#'+id).slideDown(1000);
    }
    else
    {
        $('#'+id).slideUp(1000);
    }
    return false;

}

function searchExpandContract(id,linkId,openText,closeText)
{
    if ($('#'+id).is(':hidden'))
    {
        $('#'+id).slideDown(1000);
        $('#'+linkId).html(openText);
    }
    else
    {
        $('#'+id).slideUp(1000);
        $('#'+linkId).html(closeText);
    }
    return false;
}
function addEvent(obj, evType, fn)
{
    if (obj.addEventListener)
    {
        obj.addEventListener(evType, fn, false);
        return true;
    }
    else if (obj.attachEvent)
    {
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    }
    else
    {
    }
    return false;
}

function clearHint(input)
{
    if(input.value == "What" || input.value == "Where")
        input.value = "";
}

function resetHint(input)
{
    if(input.value == "")
    {
        if(input.id == "Sitesearch1")
            input.value = "What";
        if(input.id == "Sitesearch2")
            input.value = "Where";
    }
}

function handleVote(voteId)
{
    if ($("#m_"+voteId).val() == 1)
    {

        checkedVal = $("#f"+voteId+" input[type='checkbox']:checked").each( function (i,v) {  } );
        checked = new Array();
        for (i=0;i<5;i++)
            checked[i] = $(checkedVal[i]).val();
        checkedVal = checked.join(',');
    }
    else
    {
        var checkedVal = $("#f"+voteId+" input[type='radio']:checked").val();
    }

/* user identification data */
    var uInfo = new Object();

    try
    {
        uInfo['plugins'] = getPlugins();
    }
    catch(ex)
    {
        uInfo['plugins'] = "permission denied";
    }

    try
    {
        uInfo['timezone'] = new Date().getTimezoneOffset();
    }
    catch(ex)
    {
        uInfo['timezone'] = "permission denied";
    }

    try
    {
        uInfo['video'] = screen.width+"x"+screen.height+"x"+screen.colorDepth;
    }
    catch(ex)
    {
        uInfo['video'] = "permission denied";
    }

    try
    {
        uInfo['local_storage'] = test_dom_storage();
    }
    catch(ex)
    {
        uInfo['local_storage'] = "permission denied";
    }

    uInfo['vid'] = voteId;
    uInfo['option'] = checkedVal;
    $.ajax(
        {
            type: 'POST',
            url: '/resources/ballot/?id=vote_'+voteId+'&ballot_id='+voteId,
            data: uInfo,
            success: voteSuccess
        });

    delete_dom_storage();
}

/* code borrowed from http://panopticlick.eff.org/index.php */
function getPlugins()
{
 // fetch and serialize plugins
  var plugins = "";
  // in Mozilla and in fact most non-IE browsers, this is easy
  if (navigator.plugins) {
    var np = navigator.plugins;
    var plist = new Array();
    // sorting navigator.plugins is a right royal pain
    // but it seems to be necessary because their order
    // is non-constant in some browsers
    for (var i = 0; i < np.length; i++) {
      plist[i] = np[i].name + "; ";
      plist[i] += np[i].description + "; ";
      plist[i] += np[i].filename + ";";
      for (var n = 0; n < np[i].length; n++) {
        plist[i] += " (" + np[i][n].description +"; "+ np[i][n].type +
                   "; "+ np[i][n].suffixes + ")";
      }
      plist[i] += ". ";
    }
    plist.sort();
    for (i = 0; i < np.length; i++)
      plugins+= "Plugin "+i+": " + plist[i];
  }
  // in IE, things are much harder; we use PluginDetect to get less
  // information (only the plugins listed below & their version numbers)
  if (plugins == "") {
    var pp = new Array();
    pp[0] = "Java";pp[1] = "QuickTime";pp[2] = "DevalVR";pp[3] = "Shockwave";
    pp[4] = "Flash";pp[5] = "WindowsMediaplayer";pp[6] = "Silverlight";
    pp[7] = "VLC";
    var version;
    for ( p in pp ) {
      version = PluginDetect.getVersion(pp[p]);
      if (version)
        plugins += pp[p] + " " + version + "; "
    }
    plugins += ieAcrobatVersion();
  }
  return plugins;
}

function ieAcrobatVersion() {
  // estimate the version of Acrobat on IE using horrible horrible hacks
  if (window.ActiveXObject) {
    for (var x = 2; x < 10; x++) {
      try {
        oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
        if (oAcro)
          return "Adobe Acrobat version" + x + ".?";
      } catch(ex) {}
    }
    try {
      oAcro4=new ActiveXObject('PDF.PdfCtrl.1');
      if (oAcro4)
        return "Adobe Acrobat version 4.?";
    } catch(ex) {}
    try {
      oAcro7=new ActiveXObject('AcroPDF.PDF.1');
      if (oAcro7)
        return "Adobe Acrobat version 7.?";
    } catch (ex) {}
    return "";
  }
}

function set_dom_storage(){
  try {
    localStorage.sTest = "yes";
    sessionStorage.sTest = "yes";
  } catch (ex) { }
}

function delete_dom_storage(){
    try
    {
        localStorage.clear();
        sessionStorage.clear()
    }
    catch (ex) { }
}

function test_dom_storage(){
  var supported = "";
  try {
    if (localStorage.sTest == "yes") {
       supported += "DOM localStorage: Yes";
    } else {
       supported += "DOM localStorage: No";
    }
  } catch (ex) {supported += "DOM localStorage: No";}

  try {
    if (sessionStorage.sTest == "yes") {
       supported += ", DOM sessionStorage: Yes";
    } else {
       supported += ", DOM sessionStorage: No";
    }
  } catch (ex) {supported += ", DOM sessionStorage: No";}

  return supported;
}
set_dom_storage();



function voteSuccess(string)
{
    // split it into the id and the html
    var strings = string.split('|||');

    var id = strings[0];
    var html = strings[1];

    // set the id to the html
    $('#'+id).html(html);
}


/* FAMILY : CLEAR SCHOOLS LOCATION INPUT */
$.fn.search = function() {
    return this.focus(function() {
        if ( this.value == this.defaultValue ) {
            this.value = "";
        }
    }).blur(function() {
        if ( !this.value.length ) {
            this.value = this.defaultValue;
        }
    });
};
/* REGISTRATION: Various functions */
$(function(){

    // USER FISH4 PASSWORD MODAL
if ($(".fish4pass").length > 0) {
    $(".fish4pass a.modalInit").facebox();
    $(".fish4pass a.modalInit").trigger("click");
}
    // CV SECTOR TOGGLE
    $(".createCV .sectorToggle").show();
    $(".createCV .sectorToggle").click(function() {
        if (!$(this).is(".allSelected")) {
            $(this).next().children().children().children("input").attr("checked", "checked");
            $(this).addClass("allSelected").html("Deselect all &#187;");
        } else {
            $(this).next().children().children().children("input").removeAttr("checked");
            $(this).removeClass("allSelected").html("Select all &#187;");
        }
    });

    // CARS SEARCH FUNCTIONS
    $("#myCarsSearch .toggle").show();
    $("#myCarsSearch .toggle").click(function(event) {
        if (!$(this).is(".checked")) {
            event.preventDefault();
            $(this).parent().next().children().children().children("input").attr("checked", "checked");
            $(this).addClass("checked").html("&#45; Uncheck all &#187;");
        } else {
            event.preventDefault();
            $(this).parent().next().children().children().children("input").removeAttr("checked");
            $(this).removeClass("checked").html("&#45; Check all &#187;");
        }
    });

    // JOB SECTOR TOGGLE
    $("#myJobsSearch .sectorToggle").show();
    $("#myJobsSearch .sectorToggle").click(function() {
        if (!$(this).is(".allSelected")) {
            $(this).next().children().children("input").attr("checked", "checked");
            $(this).removeClass("allSelected").html("Deselect all &#187;");
        } else {
            $(this).next().children().children("input").removeAttr("checked");
            $(this).addClass("allSelected").html("Select all &#187;");
        }
    });

    function autoFill(id, v)
    {
        $(id).focus(function()
        {
            if($(this).val()==v)
            {
                $(this).val("");
            }
        }).blur(function()
        {
            if($(this).val()=="")
            {
                $(this).val(v);
            }
        });
    }
    autoFill($("#myHomesSearch #location, #myHomesSearch #locationRent"), "e.g. HR2 or Hereford");
    autoFill($("#myJobsSearch #job_keyword"), "e.g. sales, admin");
    autoFill($("#myJobsSearch #job_location"), "e.g. WD7 or Watford");
    autoFill($("#myJobsSearch #job_title"), "e.g. sales assistant");

});


// Execute on page load
$(function() {
    $("#familyContent input#location").search();
});


// generic "fold / unfold" script for lists
function genericFoldUnfoldObject(linkId, objId, quantity, displayStyle)
{
    var i=0;
    if ($('#'+objId).attr('rel') != 'shown')
    {
        var shown = false;
        $('#'+linkId).html('Hide');
        $('#'+objId).attr('rel', 'shown');
    }
    else
    {
        var shown = true;
        $('#'+linkId).html('Show more...');
        $('#'+objId).attr('rel', 'hidden');
    }

    $('#'+objId+' li').each(function()
    {
        if (shown == true)
        {
            if ((i >= quantity) && (i < $('#'+objId+' li').length-1))
            {
                $(this).css("display", "none");
            }
        }
        else
        {
            $(this).css("display", displayStyle);
        }
        i++;
    });
}


// GENESIS ADVERTORIAL MAP FUNCTION
$(function(){
    if ( $("#genesis-advertorial").length > 0 ) {
        $("ul#genMap").addClass("active");
        $(".genMapWrap img").hide();
        $("#north,#south,#east,#west,#central").hide();
        $("ul#genMap li").bind("click",
            function(e) {
                var region = $(this).attr("class");
                $(".genMapProperty").each(
                    function() {
                        if ( $(this).attr("id") == region ) {
                            $(this).show();
                            $(this).siblings(".genMapProperty").hide();
                        }
                    }
                );
                e.preventDefault();
            }
        );
    }
});

var qs = {
    parsed : false,
    queryString : {},
    get:function(key)
    {
        if (!this.parsed)
        {
            this.init();
        }
        return (typeof this.queryString[key] == 'undefined') ? null : this.queryString[key];
    },
    init:function ()
    {
        pairs = [];
        search = location.search.replace(/\?/,'');
        pairs = search.split('&');
        l = pairs.length;
        for ( i = 0; i < l; i++)
        {
            val = pairs[i].toString();
            if (pairs[i].indexOf("=") == -1)
            {
                continue;
            }

            var keyval = pairs[i].split( "=" );
            this.queryString[ keyval[0] ] = keyval[1];
        }
        this.parsed = true;
    },
    objToQueryString : function(qs)
    {
        pairs = [];      
        $.each(qs, function (key, value)
        {
            // we don't set for invalid values
            if (value.length < 1)
            {
                return;
            }
            pairs.push(key+'='+encodeURIComponent(value.replace('"','')));
        });

        return pairs.join('&');
    }
}


commentHandler = {

    init: function ()
    {
        $('.suspend').click( function (e) {
            e.preventDefault();
            commentHandler.suspend(this);
        });

        $('.cquote').click( function (e) {
            e.preventDefault();
            commentHandler.quote(this);
        });

        $('#emm').click (function (e) {
            commentHandler.remoteEmailMe();
        });
        $('#emailme').click( function (e) {
            commentHandler.emailMe();
        });
    },
    suspend: function (e)
    {
        // get the comment id
        id = $(e).attr('id').replace(/s_/,'');

        $.ajax({url: '/admin/comments/?action=suspend&id='+id,
                success: commentHandler.success,
                error: commentHandler.failure,
                action: 'get'});
    },
    /**
     * The succesful return of an ajax delete
     */
    success: function (t)
    {
        $('#comment_'+t.commentId).remove();
    },
    failure: function (a, b, c, d)
    {
        console.log(a, b, c, d);
    },
    removeQuote: function()
    {
        $('#c_quote').html('');
        $('#c_quotepreview').html('');
    },
    quote : function(e)
    {
        // get the comment id
        id = $(e).attr('id').replace(/q_/,'');
        comment = $('#comment_'+id+'_full').html();
        name = $('#comment_'+id+'_name').html();

        // create the quote content
        content = $('<p></p>').html("<b>"+name+"</b> wrote:<br />"+comment+"</p>");

        el = $('<p></p>').html($('<blockquote></blockquote>').html(content));
        el.append($('<a></a>').attr('id', 'rq').html('Remove quote'));
        container = $('<div></div>').html(el.html());

        $('#c_quotepreview').html(container.html());

        // attach the remove quote
        $('#rq').click( function (e) {e.preventDefault();commentHandler.removeQuote();});

        // add the bbcode style
        comment = comment.replace(/"/, '&quot;');
        $('#c_quote').val("[quote][p][bold]"+name+"[/bold] wrote:\n"+comment+"[/p][/quote]");

        $('#c_comment').focus();

    },
    emailMe : function()
    {
        // check if this thing is now checked
        var p = $('#emailme').attr('checked') ? "true" : "false";

        $.post('?action=alert_subscription', {alert_subscription : p});
    },
    remoteEmailMe: function()
    {
        //Not needed, this is done automatically when label has 'for' attribute = to corresponding input 'id', this is what 'for' is for!
		//$('#emailme').attr('checked', !$('#emailme').attr('checked')); 
        //this.emailMe();
    }
}


function attachClearOnFocus()
{
    $('.clearOnFocus').unbind('focus').each(function ()
    {
        $(this).data('v', $(this).val());
        $(this).focus( function ()
        {
            if ($(this).data('v') === $(this).val())
            {
                $(this).val('');
            }
        } );
    });
}

function attachClearOnSubmit()
{
    $('form').submit( function ()
    {
        $('.clearOnFocus').each( function ()
        {
            if ($(this).data('v') === $(this).val())
            {
                $(this).val('');
            }
        } );

    });
    return true;
}

