/**
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,.pagination a").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
        //Hide the map as this is no longer required as per new requirement
        //$('.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 });
	    $(".colorboxTerms").colorbox({width:600, inline:true});/*tb*/
        $(".colorboxExt").click(function() {
            var popContents = $(this).attr('href') + ' .modalContent';
            $.fn.colorbox({ title: $(this).attr('title'), opacity: .9, href: popContents, open: true });
            return false;
        });
        $(".colorboxInPage").click(function() {
            var popContents = $(this).attr('href') + ' .centreCol';
            $.fn.colorbox({ title: $(this).attr('title'), opacity: .9, href: popContents, open: true, width: 500, height: 400 });
            return false;
        });
		
		$().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").not('.gallery li .imageSelect 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>")
			}
		})
		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);
		});*/

		/* Media gallery */
		
		$('.OMChidden').hide();
		$('.imageSelect').addClass('inactive');
		$("a.colorboxPhotoConfirm").colorbox({inline:true,opacity:.9}, function(){
			$('#omcPrivacy').css('width','100%').hide();
			$.fn.colorbox.resize();
		});
		
		$(".imageSelect input.submit").attr('disabled', 'disabled');
		$('.imageSelect input:checkbox').livequery('click', function (event) {
			if ($(this).is(':checked')) {
				$(this).parent('.imageSelect').removeClass('inactive');
				$('input.submit').removeAttr('disabled');
			}
			else {
				$(this).parent('.imageSelect').addClass('inactive');
				$(".imageSelect input.submit").attr('disabled', 'disabled');
			}
		});
		$('.imageSelect').before($('#omcPrivacy'));
		$(".imageSelect a").click(function() {
			$('#omcPrivacy').toggle();
			$.fn.colorbox.resize();
			return false;
		});
		$('.reuseApplication').addClass('reuseApplicationJs');
		$('#savedAppBox').css('display', 'block');
		$('.toggleBoxApplication').click(function() {
		    $('.reuseApplication').slideToggle();
		    return false;
		});

		$().toggleBoxWithLink("forgotPassword");
		$().toggleBoxWithLink("updatePersonalDetails", "fast");

		$(".toggleBox").each(function(i) {
		    $(this).addClass("toggleRef" + i).hide();
		    //$(this).before('<p class="add addLarge"><a href="javascript:;" onclick="openToggleBox(this,\'toggleRef'+i+'\')">New User?</a></p>')
		    $(this).before('<div class="submit"><a href="javascript:;" onclick="openToggleBox(this,\'toggleRef' + i + '\')" class="button"><span>New User?</span></a></div>')
		});
        /* Comments */

        $(".colorboxComment").colorbox({ width: 370, inline: true });

        $("#cbComment input.submit").click(function() { return areCommentsValid(); });

        $("p.userComments a").toggle(
	    function() {
	        $(this).text($(this).text().replace("Hide", "Show")).removeClass("close").addClass("add");
	        $("div.userComments").slideUp();
	    },
	    function() {
	    $(this).text($(this).text().replace("Show", "Hide")).removeClass("add").addClass("close");
	        $("div.userComments").slideDown();
	    });
		
		//Javascript check
		$('input.jscheck').attr('value','true')
		
	});
})(jQuery);



/* ---------- Functions -------- */

/*tb - all code until... */
jQuery.fn.toggleBoxWithLink = function(className, speed) {
    if (speed == null) {
        speed = "normal";
    };
    if ($("div." + className) != null)
	{
    $("div." + className).hide();
    $("p." + className + " a, a." + className + ", h4." + className).click(function() {
        $(this).slideUp(speed);
        $("div." + className).slideDown(speed);
        return false;
    });

	}
	
}
/*... here. tb*/

function openToggleBox(link, id) {
    $(link).slideUp();
    $("." + id).slideDown();
}

function colorboxInPage(lnk) {
    var popContents = $(lnk).attr('href') + ' .centreCol';
    $(lnk).colorbox({ title: $(lnk).attr('title'), opacity: .9, href: popContents, open: true, width: 500, height: 400 });
    return false;
};

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;
}

function clickButton(e, buttonid) {
    var evt = e ? e : window.event;
    var bt = document.getElementById(buttonid);

    if (bt) {
        if (evt.keyCode == 13) {
            bt.click();
            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>")
    });
	
    /* Comments functions */

    function areCommentsValid() {
        var isValid = true;

        if ($("#cbComment input.commentName").val() == "") {
            isValid = false;
            $("#cbComment p#nameError").fadeIn("fast", function() { $(this).removeClass("hide"); });
        }
        else if (!$("#cbComment p#nameError").hasClass("hide"))
            $("#cbComment p#nameError").fadeOut("fast", function() { $(this).addClass("hide"); });

        if ($("#cbComment input.commentTown").val() == "") {
            isValid = false;
            $("#cbComment p#townError").fadeIn("fast", function() { $(this).removeClass("hide"); });
        }
        else if (!$("#cbComment p#townError").hasClass("hide"))
            $("#cbComment p#townError").fadeOut("fast", function() { $(this).addClass("hide"); });

        if ($("#cbComment input.commentEmail").val() == "") {
            isValid = false;
            $("#cbComment p#emailError").fadeIn("fast", function() { $(this).removeClass("hide"); });
        }
        else if (!$("#cbComment p#emailError").hasClass("hide"))
            $("#cbComment p#emailError").fadeOut("fast", function() { $(this).addClass("hide"); });

        if ($("#cbComment input.commentEmail").val() != "" && !$("#cbComment input.commentEmail").val().match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) {
            isValid = false;
            $("#cbComment p#emailFormatError").fadeIn("fast", function() { $(this).removeClass("hide"); });
        }
        else if (!$("#cbComment p#emailFormatError").hasClass("hide"))
            $("#cbComment p#emailFormatError").fadeOut("fast", function() { $(this).addClass("hide"); });
        
        if ($("#cbComment textarea.commentText").val() == "") {
            isValid = false;
            $("#cbComment p#textError").fadeIn("fast", function() { $(this).removeClass("hide"); });
        }
        else if (!$("#cbComment p#textError").hasClass("hide"))
            $("#cbComment p#textError").fadeOut("fast", function() { $(this).addClass("hide"); });

        return isValid;
    }
	
	//Open colorbox on demand
	function openModal(lnk) {
		var lnk = "ForgottenPassword.aspx";
		var fields = lnk.split(".")
		var urlJS = "";
		for (i=0;i < fields.length;i++) {
			if (i == 1) {
			   urlJS += "JS.";
			} 
			urlJS += fields[i] 
		}
		var popContents = urlJS;
		$.fn.colorbox({ opacity: .9, href: popContents, width:'500px',height:'400px',open: true, iframe:true });
		$("#cboxOverlay").unbind('click');
	};
