/**
customised javascript for Norfolk Constabulary
**/
  
(function($) {
    $(function() {
        $(".jshide").hide();
		var domainRef = "";
		
		if (location.href.substring(7,10) == "www"){
			domainRef = ""
		}else{
			domainRef = "/norfolkweb/"
		}
	
        /*jQuery("a[href*='http://']").not(".meetTheTeam, .mainStory a, .videoPlayer a, .listenIcon, .featured a, a:has(img), .button, .del a, .digg a, .fbook a").each(function() {

            $(this).attr({ "title": $(this).attr("title") + " (Links to an external website and opens in a new window)" }).addClass("external").append('<img width="15" height="10" src="/images/icon_external-link.gif" alt="" />');
            window.open($(this).href);
            return false;
        });*/
		
		$("a:not(.addthis_button)").each(function(){
			if ($(this).parent().is(":contains('PDF, ')")){
				$(this).addClass("pdf");
			}
			if ($(this).parent().is(":contains('XLS, ')")){
				$(this).addClass("excel");
			}
			if ($(this).parent().is(":contains('DOC, ')")){
				$(this).addClass("word");
			}
			if ($(this).parent().is(":contains('PPT, ')")){
				$(this).addClass("ppt");
			}
			if ($(this).parent().is(":contains('JPG, ')")){
				$(this).addClass("image");
			}
			if ($(this).parent().is(":contains('PNG, ')")){
				$(this).addClass("image");
			}
			if ($(this).parent().is(":contains('GIF, ')")){
				$(this).addClass("image");
			}
		})

		
		 if (jQuery.browser.msie) {
			$("a[href*='http://']").not(".colorboxLink").each(function() {
				//return this.hostname && this.hostname !== location.hostname;
			 }).addClass("external").attr({
				"target": "_blank",
				"title": "Link to an external website"
			}).not(".meetTheTeam, .mainStory a, .videoPlayer a, .listenIcon, .featured a, a:has(img), .button, .del a, .digg a, .fbook a").append('<img width="15" height="10" src="' + siteRoot + 'images/icon_external-link.gif" alt="Link to an external website" />');
			
			$(".np-partners a").addClass("external").attr({
				"target": "_blank",
			"title": "Link to an external website"
			})
			
			$(".thumbsContainer .clips li").hover(
			function(){
				$(this).css({"background-color":"#e1e1e1"});
			},
			function(){
				$(this).css({"background-color":"#f1f1f1"})
			})
		
		}else{

			$('a').filter(function(){
				return this.hostname && this.hostname !== location.hostname;
			}).addClass("external").attr({
				"target": "_blank",
			"title": "Link to an external website"
			}).not(".meetTheTeam, .mainStory a, .videoPlayer a, .listenIcon, .featured a, a:has(img), .button, .del a, .digg a, .fbook a, .details a").append('<img width="15" height="10" src="' + siteRoot + 'images/icon_external-link.gif" alt="Link to an external website" />');
			
			$(".np-partners a").addClass("external").attr({
				"target": "_blank",
				"title": "Link to an external website"
			});	
		}
		
		
        $(".share").removeClass("hideSharelinks")
        $(".del a").click(function() {
            sendDeliciousLink();
            return false;
        });
        $(".digg a").click(function() {
            sendDiggLink();
            return false;
        });
        $(".fbook a").click(function() {
            sendFacebookLink();
            return false;
        });
        //auto fill search field
       // autoFill($("fieldset.searchForm .Search"), "Search:");
        autoFill($(".neighbourhood .text"), "Enter your postcode");
        autoFill($(".policeSearchPostcode"), "Enter your postcode");

        /* styles for IE 6 */
        if (jQuery.browser.msie) {
            if (parseInt(jQuery.browser.version) == 6) {
                hoverIE($(".mainNav ol li"));
                hoverIE($(".feature .featureList li.on a, .feature .featureList li"));
            }
        }

        // piano keys (alternate line colourings) for tables
        pianoKeys();

        // alternating items
        toggleBlocks();

        // 'show more/less' functionality
        showHide();

        // a-z listing page
        azNav();

        // enable tabbed navigation
        contentTabs();

        // my neighbourhood section - toggle region changer
        //$("#select-neighbourhood").hide();

        $("a[href=#select-neighbourhood]").click(function() {
            $("#select-neighbourhood").slideToggle("fast");
            return false;
        });

        //switch homepage feature items on rollover
        var switches = $('#switches li');
        var slides = $('#slides div');
        switches.each(function(idx) {
            $(this).data('slide', idx);
        }).hover(function() {
            switches.removeClass('active');
            slides.removeClass('active');
            $(this).addClass('active');
            $(slides[$(this).data('slide')]).addClass("active");
        });

        //append search map image and link
        $('.neighbourhood fieldset').after('<a href="#mapContainer" title="Find your area" class="colorboxMap mapLink"><img src="' + siteRoot + 'images/interface/search_map.jpg" alt="find it on the map" /></a>');

        //hide for now - m.
        /*
         * 
        if($('.colorboxMap').size()){
        $("body").append('<div class="hidden"><div id="mapContainer"><div id="mapObj">view map</div></div></div>')
        }
        */
        // add text resizer
        $("#pageTools").append('<a href="' + siteRoot + 'accessibility.aspx">Accessibility: </a>: <a class="normal" href="#non" title="Small text">A</a> <a class="medium" href="#non" title="Medium text">A</a> <a class="large" href="#non" title="Large text">A</a>');

		var flashvars = {},
		params = {},
		attributes = {};
		flashvars.flashDataURL = "/flash/";
		swfobject.embedSWF(siteRoot + "flash/Norfolk_Police_Neighbourhoods.swf", "mapObj", "860", "580", "9.0.0",false,flashvars, params, attributes);

        $(".colorboxLink").each(function() {
            var contentID = $(this).next().children("div").attr("id");
            $(this).attr("href", "#" + contentID).addClass("colorboxInfo").removeClass("colorboxLink");
        })

        $(".colorboxMap").colorbox({ width: "900", height: "660", inline: true });
        $(".colorboxPhoto").colorbox();
        $(".colorboxInfo").colorbox({ width: 300, height: 450, inline: true });
		
		$().bind('cbox_open', function(){$('object, embed').not("#mapObj").css({'visibility':'hidden'});});
		$().bind('cbox_closed', function(){$('object, embed').css({'visibility':'inherit'});});
		
        //Date Picker for Job Application (using jQuery UI)
        $(".datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: "dd/mm/yy",
			maxDate: '+0m',
			minDate: '-100y +0m',
			yearRange: '-100:+100'
        });
		//Date Picker for 'report a crime' form
		$(".dobpicker").datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: "dd/mm/yy",
			maxDate: '+0m',
			minDate: '-100y +0m',
			yearRange: '-100:+100'
		});
		$(".datepickerDateTo").datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: "dd/mm/yy",
			maxDate: '+0m',
			minDate: '-60y +0m',
			yearRange: '-60:+60'
		});


        if ($('#archiveItems')) {
            $('#archiveItems').hide();
            $('.archiveContainer').append("<p class='addCross'><a href='#archiveItems'>View archived actions</a></p>")
        }
      	var iconPath = siteRoot+"images/interface/icon_zoom.gif"
        $(".gallery li a").append("<img src='"+iconPath+"' class='zoomIcon'/>")
		
		//create caption for content images from alt text
		$(".contentCol img").not(".mapLink img, .zoomIcon, #slides img, .crimeMap img, #policeStationMap img, .result-blocks img, .mainStory img, .col img, .stationResults img, .gallery img, table img, .external img, .sitmp0 img, .sitmp1 img, .sitmp2 img, .addthis_button img").each(function() {
		var imgWidth;
		if ($.browser.msie && $.browser.version == "6.0") {
           imgWidth = $(this).width();
        }else{
			imgWidth = $(this).width() -5;
		}
			//nb: detect width of img and then set width of caption (inline?)
			if ($(this).attr('class') == "ImmTextAlign_Center") {
				$(this).wrap("<div></div>");
				$(this).parent().addClass("ImmTextAlign_Center")
				$(this).after("<span class='caption ImmTextAlign_Center' style='width:"+imgWidth+"px'>" + $(this).attr("alt") + "</span>")
			}else if ($(this).attr('class') == "ImmControlAlign_Right") {
				$(this).after("<span class='caption ImmControlAlign_Right' style='width:"+imgWidth+"px'>" + $(this).attr("alt") + "</span>")
			}else if ($(this).attr('class') == "ImmControlAlign_Left") {
				$(this).after("<span class='caption ImmControlAlign_Left' style='width:"+imgWidth+"px'>" + $(this).attr("alt") + "</span>")
			}else{
				$(this).after("<span class='caption' style='width:"+imgWidth+"px'>" + $(this).attr("alt") + "</span>")
			}
		})
		
		
		// from scrollto library to amend - add object detection to detect police station results
		
		if($(".stationResults").size()){
			$("html,body").animate({scrollTop: $(".stationResults").offset().top}, 1100);
		}
		
		
		$(".sitemap").addClass("siteMapJs");

		//add markup to sitemap page
		var count = 0;

		$(".sitemap").children().each(function(){
			if ($(this).hasClass(".sitmp0")){
				$(this).before("<img src='images/interface/icon_add.gif' alt='open sitemap section' class='openSection siteMap"+count+"'/>")
				count++
			}else{
				$(this).addClass("nested"+count)
			}
		})
		for(var i=1;i<=count;i++){
			$(".nested"+i).show().wrapAll("<div class='subSection container"+(i-1)+" jshide'>");
		}
		
		$(".openSection").toggle(function(){
			$(this).attr("src","images/interface/icon_remove.gif");
			$(this).nextAll(".subSection:first").slideDown("fast");
		},function(){
			$(this).attr("src","images/interface/icon_add.gif");
			$(this).nextAll(".subSection:first").slideUp("fast");
		})
		
		/*$(".details a[href^=mailto]").each(function(){
			var mailto = $(this).text().split("@");
			var newMailto = mailto[0]+"<wbr>@"+mailto[1];
			$(this).html(newMailto);
		});*/
	});
})(jQuery);



/* ---------- Functions -------- */

function autoFill(id, v){
    jQuery(id).attr({
        value: v
    }).focus(function(){
        if(jQuery(this).val()==v){
            jQuery(this).val("").css({
                color: "#999"
            });
        }
    }).blur(function(){
        if(jQuery(this).val()==""){
            jQuery(this).val(v);
        }
    });
}

function pianoKeys(){
	// if there is an odd number of rows, only colour the even ones, and vice versa.
	// this is to make sure that the last row is always grey
	jQuery("table:not(.plain) tbody tr").size() % 2 ? jQuery("table:not(.plain) tbody tr:even").addClass("alt") : 	jQuery("table:not(.plain) tbody tr:odd").addClass("alt");
}

function toggleBlocks (){
	if(jQuery(".toggleHolder").size()){
		jQuery(".toggleHolder .toggleItem:odd").hide();
		jQuery(".toggleHolder .toggleControl").click(function(){
			jQuery(this).parents(".toggleItem").siblings(".toggleItem").toggle();
			jQuery(this).parents(".toggleItem").toggle();
			return false;
		})
	}
}
function showHide (){
	if(jQuery(".more-toggle").size()){
		jQuery(".more-toggle").each(function(){
			var $control = jQuery(this).siblings("h3.expand");
			$control.addClass("togglePlus");
			jQuery(this).hide();
			$control.click(function(){
				jQuery(this).siblings(".more-toggle").slideToggle("fast");
				jQuery(this).toggleClass("togglePlus").toggleClass("toggleMinus");
				return false;
			})
		})
	}
}

function contentTabs(){
	if(jQuery(".tab-holder").size()){
		jQuery(".tab-holder").each(function(){
			if(jQuery(this).hasClass("hide-headers")){jQuery(".tab > h3", this).hide();}
			
			jQuery(this).addClass("tab-active").prepend('<ul class="tab-nav clearfix" />')
			
			for(var i=0; i<jQuery("div", this).size(); i++){
				jQuery(".tab-nav", this).append('<li><a href="#">'+jQuery("div:eq("+i+") h3:eq(0)", this).text()+'</a></li>');
				
				jQuery(".tab-nav li:eq("+i+")", this).click(function(e){
					jQuery(this).addClass("active").siblings().removeClass("active");
					var $id = jQuery(this).parent().children("li").index(this);
					jQuery(this).parents(".tab-holder").children(".tab").addClass("hide").end().children(".tab:eq("+$id+")").removeClass("hide");
					return false;
				})
			}
			jQuery(".tab-nav li:eq(0)", this).addClass("active");
			jQuery("> div", this).addClass("hide");
			jQuery("> div:eq(0)", this).removeClass("hide");
		});
	}
}

function azNav() {
    if (jQuery(".az").size()) {
        var jQuerycount = jQuery(".az").size();
        jQuery(".az:eq(0)").before('<ul class="az-nav" />');
        
        for (var i = 0; i < jQuerycount; i++) {
            jQuery(".az:eq(" + i + ")").addClass("b" + i);
            jQuery(".az-nav").append('<li><a href="#">' + jQuery(".az:eq(" + i + ") h3").text() + '</a></li>');
            jQuery(".az-nav li:last-child").data("id", i);

            if (jQuery(".az:eq(" + i + ") div.az-list ul").size() == 0)
                jQuery(".az-nav li:last-child").removeClass().addClass("inactive");
        }
        jQuery(".az").hide();
        jQuery(".az-nav li[class!='inactive'] a").click(function() {
            var jQueryid = jQuery(this).parent().data("id");
            jQuery(this).parent().siblings().removeClass("active")
            jQuery(this).parent().addClass("active");

            if (jQuery(".az:eq(" + jQueryid + ")").attr("class") != jQuery(".az:visible").attr("class")) {
                jQuery(".az:visible").slideUp("fast", function() {
                    jQuery(".az:eq(" + jQueryid + ")").slideDown("fast");

                });

            }
        });
        jQuery(".az-nav li:eq(0) a").click();
        jQuery(".az:eq(0)").show();
    }
}


function hoverIE(id){
  jQuery(id).hover(
      function () {
        jQuery(this).addClass("hover");
      },
      function () {
        jQuery(this).removeClass("hover");
      }
    );
}


function displayFeature(){
	
}

function sendDiggLink(){
	var description;
	var metas = $("meta")
	for (var x=0,y=metas.length; x<y; x++) {
  	if (metas[x].name.toLowerCase() == "description") {
   	 description = metas[x];
  	}
	}	
	window.open('http://digg.com/submit?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title)+'&amp;bodytext='+encodeURIComponent(description.content)+'&media=news&topic=world_news','digg','toolbar=no,scrollbars=1,width=626,height=436')
}
function sendDeliciousLink(){
	window.open('http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550');
    return false;
}
function sendFacebookLink(){
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}


 $(".archiveContainer .addCross a").live("click", function(){
     $("#archiveItems").show()
	 $(".archiveContainer .addCross").remove()
	 $('.archiveContainer').append("<p class='close'><a href='#archiveItems'>Close archived actions</a></p>")
    });
	
 $(".archiveContainer .close a").live("click", function(){
     $("#archiveItems").hide()
	 $(".archiveContainer .close").remove()
	 $('.archiveContainer').append("<p class='addCross'><a href='#archiveItems'>View archived actions</a></p>")
    });
	
	