var $ = jQuery.noConflict();
$(document).ready(function () {


	if (navigator.userAgent.toLowerCase().indexOf('opera')!=-1){
			var link = "<link type=\"text/css\" rel=\"stylesheet\" href=\"ie9.css\"/>";
		$("head link[href$='tweaks.css']").after( link ); 	
	}
	else{
		if(navigator.userAgent.toLowerCase().indexOf('msie')==-1){
			var link = "<link type=\"text/css\" rel=\"stylesheet\" href=\"css3.css\"/>";
		$("head link[href$='tweaks.css']").after( link ); 	
		}
	
	
	}
	
	if((navigator.userAgent.toLowerCase().indexOf('msie')==-1) )
	{
		var link = "<link type=\"text/css\" rel=\"stylesheet\" href=\"\"/>";
		$("head link[href$='tweaks.css']").after( link ); 	
	}
	else{
		//var link = $("<link/>").attr({type: 'text/css',media: 'screen',rel: 'stylesheet',href: 'overlay.css'});
		//$("head").append( link ); 
	//$("head link[href='/scripts/modal/jquery.fancybox-1.3.1.css']").after(link)	
	}

var host = location.host.replace("www.","").replace(".org.","")

var isdebug=true;

if (readCookie("OCMEDIT") =="ON" || readCookie("REQURL") != null) {isdebug=false}
if (location.hostname.split(".").length>1 && isdebug==false){
	LLedit = true;
	$("body").addClass("LL")
	//host = "assemblywales.org"
}
if (host.split(".").length>1){
	host="cynulliadcymru"
	temphost = location.hostname;
}
if ($(".carousel").length>0){
	//$.getScript("jquery.s80carousel.packed.js?car=ff", function() {
	  $(".carousel").s80Rotator();
	//});
}
if ($(".imagestrip").length>0){
	//$.getScript("jquery.s80imagestrip.packed.js?cbust=123", function() {
	 $(".imagestrip").s80imagestrip();
	//});
}

	$("#pstfinder_btn").click(function(e){
		if(typeof(validatePostCode) != "undefined"){
			validatePostCode();
			e.preventDefault();
		}
	})

	
	$("a img[src*='cmo']").css("margin","0");

	
	
		//$("a").each(function(){
		//	if (($("img[title*='Click this icon']",this).length>0) && ($(this).parent(".LLopt").length==0)){
		//		$(this).before("<span class=\"LLopt\">");
		//		var $nxt = $(this).next("a img[title*='Click this icon']")
		//		if ($("img[title*='Click this icon']",$nxt).length==0){
		//			$(this).after("</span>");
		//		}
		//	}
		//})

	if(typeof(LLedit) != "undefined"){$(".tabbed").addClass("LL");}
	
	var $tabs = $(".tabbed .tabs")
	var $panels = $(".tabbed .panel")
	$panels.hide(); 
	$(".tabbed .panel:first").show(); 
	$(".tabbed .tabs li:first").addClass('on'); 
	$('li a',$tabs).bind("click",function(e) { 
		e.preventDefault();
		var $tab =$(this).parents("li")
		$('li',$tabs).removeClass('on').removeClass('focus').attr("style",""); 
		$('h3',$tabs).removeClass('focus') 
		$tab.addClass('on').removeClass('focus')
		if (!$.support.opacity){
			$tab.css({"background-position":"0 -" + $tab.height()}) 
		};
		var hashid = $(this).attr('href'); 
		$panels.hide(); 
		$(hashid).fadeIn(1000); return false 
	});
	if (!$.support.opacity){
		$(".masthead .tabs li").hover(function(){
			$(this).index() ==1? 	$(this).toggleClass("hover_home"):$(this).toggleClass("hover")
			
		}, function(){$(".masthead .tabs li").removeClass("hover_home").removeClass("hover")})
		
		
	}
	
	isIE6 = !$.support.opacity && !window.XMLHttpRequest,
	isIE = !$.support.opacity
	// add CSS enhancements for anything other than ie

	
	if (isIE6){
		$(".stack ul li.current[class$='current'] a").addClass("current")
	}
	//if (isIE6){$(".rightPane .box .content").css({position:"relative"})}
	checkmaxheight()
	$(document).bind('fontresize', function(){ 
		checkmaxheight()	
	});
	
	$("embed").each(function(){
		if($(this).attr("src").indexOf("senedd.tv")!= -1){
		$(this).css({width:this.width,height:this.height})
		}
	})
	//$("a.video").click(function(e){
		//e.preventDefault();
		var flashvars = {};
		var params = {wmode:"transparent",autoplay:"true"};
		var attributes = {id: 'seneddtv'};
		if (typeof(swfobject) != "undefined"){
		swfobject.embedSWF($("a.video").attr("href"), "senedd", "530", "260", "9.0.0", false, flashvars, params, attributes );
		}

	//})
    // link behaviours
    $("body a[href]").each(function () {
		var $atag = $(this);
        // accessibility focus  
        $atag
			.focus(function () {

				//add focus class to parent elements for tabs
			    if ($atag.parents(".tabs").length > 0 ){
					//inpage? inpage:toptabs
					$atag.parent("h3").length > 0 ? $atag.parent().parent().toggleClass("focus"):$atag.parent().toggleClass("focus")}
				else{
					// dont do this for carousel controls
					if ($atag.parents(".control").length > 0 ){
						$atag.parent().toggleClass("active")
					}
					else{
					  	$atag.toggleClass("focus")
					}
				}
				if($atag.parents(".hide").length > 0){
					$atag.parent().removeClass("hide").addClass("rehide")
				}						
			})
			.blur(function () {
				if ($atag.parents(".tabs").length > 0 ){
					//inpage? inpage:toptabs
					$atag.parent("h3").length > 0 ? $atag.parent().parent().toggleClass("focus"):$atag.parent().toggleClass("focus")
				}
				else{
					$atag.toggleClass("focus")
					}
				if($atag.parents(".rehide").length > 0){
					$atag.parent().removeClass("rehide").addClass("hide")
				}
			})
			.mousedown(function () {
			    $atag.removeClass("focus").unbind("focus").unbind("blur")
			})

        //external links
		// not on staging, not javascript, not hashlinks
		
		if(($atag.attr("href").indexOf(host)==-1))
        if (this.hostname &&  (this.hostname.indexOf(host) == -1 && this.hostname.indexOf(temphost) == -1 ) && ($("span.external", this).length == 0) && (this.href.indexOf("javascript") == -1) && (this.href.length != -1)) {
            if (($atag.parent().parent().parent(".tabs").length == 0) && ($atag.parent().parent(".share").length == 0)) {
                $atag.attr("target", "_new")
                var $title = ""
                var $title = $atag.attr("title")
                $atag.attr("title", $title + " [Yn agor ffenestr newydd]")
                if ($("img", this).length == 0) {
                    $atag.text(function () { return $atag.text().toString() }).append("<span class=\"external\" style=\"display:inline-block\" ><span class=\"hide\"> [Yn agor ffenestr newydd]</span></span>")
                }

            }
        }


        // general doc links icons
		
        if (($atag.attr("href").indexOf(".pdf") > -1)){
			if($atag.parents("li").length>0){
			 $atag.parent("p").length > 0 ? $atag.unwrap().parent("li").addClass("pdf"):$atag.parent("li").addClass("pdf")
			 }
			 else{
			  $("img",$atag).length > 0 ? $atag.attr("title","Pdf document " + $("img",$atag).attr("alt")): $atag.addClass("pdf")
			 }

        }
		
        if (($atag.attr("href").indexOf(".doc") > -1)||($atag.attr("href").indexOf(".docx") > -1)){
			if($atag.parents("li").length>0){
			 $atag.parent("p").length > 0 ? $atag.unwrap().parent("li").addClass("doc"):$atag.parent("li").addClass("doc")
			 }
			 else{
			  $atag.addClass("doc")
			 }
			
        }
        if (($atag.attr("href").indexOf(".xls") > -1)||($atag.attr("href").indexOf(".xlsx") > -1)||($atag.attr("href").indexOf(".csv") > -1)){
			if($atag.parents("li").length>0){
			 $atag.parent("p").length > 0 ? $atag.unwrap().parent("li").addClass("xls"):$atag.parent("li").addClass("xls")
			 }
			 else{
			  $atag.addClass("xls")
			 }
        }
		if (($atag.attr("href").indexOf(".ppt") > -1)||($atag.attr("href").indexOf(".pptx") > -1)){
						if($atag.parents("li").length>0){
			 $atag.parent("p").length > 0 ? $atag.unwrap().parent("li").addClass("xpptls"):$atag.parent("li").addClass("ppt")
			 }
			 else{
			  $atag.addClass("ppt")
			 }
        }
		if (($atag.attr("href").indexOf(".zip") > -1)||($atag.attr("href").indexOf(".rar") > -1)){
			if($atag.parents("li").length>0){
			 $atag.parent("p").length > 0 ? $atag.unwrap().parent("li").addClass("zip"):$atag.parent("li").addClass("zip")
			 }
			 else{
			  $atag.addClass("zip")
			 }
        }
	
    })

	$(".cols h3 a").css({"word-wrap":"break-word"})
	$(".elipsis").css({"display":"inline-block"})
	
	// table row styles
	$(".cms table tr:odd").addClass("odd")
	// table interaction 
		$(".cms table.expand")
		.attr("tabindex","0")
		.before($("<a class=\"open\">Expand data table</a>")
					.click(function(){
					 if ($(this).html().indexOf("Expand") >= 0) {
						$(this).html($(this).html().replace("Expand", "Reset"));
						$(this).next().css({position:"absolute",width:"50%","box-shadow": "-1px 2px 2px #000","-moz-box-shadow": "0px 0px 5px #888"})
					}
					else {
						$(this).html($(this).html().replace("Reset", "Expand"));	
						$(this).next().css({position:"",width:"500px","box-shadow": "0 0 0 #000","-moz-box-shadow": "0 0 0 #000"})						
					}})
				)
		
		//  flash accessiblity
		$(".flash-text h2.title").each(function(){
			var detail = $(this).next().addClass("detail").hide().attr('aria-hidden',"true")
			$(this).after($("<p><a class=\"open\" tabindex=\"0\" href=\"#\">show video description</a></p>"))

		})

		$("a.open").focus(function(e){
			$(this).click(e)
		})
			

		$("a.open").click(function(e){
			e.preventDefault();
			var $detail = $(this).parent().next("div.detail")
				if ($detail.is(":hidden")){
					$detail.slideToggle("fast")
					$(this).text(function(){ return $(this).text().replace("show","hide")})
					$detail.attr('aria-hidden',"false");
				}
				else{
					$detail.slideToggle()
					$(this).text(function(){ return $(this).text().replace("hide","show")})
					$detail.attr('aria-hidden',"true");
				}
				$(this).toggleClass("show")
			})
				


    // A-Z links behaviour
    $("#divDateRange a").click(function () {
        $("#divDateRange a").removeClass("active")
        $(this).addClass("active")
    })
    // policy browser A-Z links behaviour
    $("#divAlphaRange a").click(function () {
        $("#divAlphaRange a").removeClass("active")
        $(this).addClass("active")
    })
    // in page tabs behaviour
    $(".contentPane .tabs li").click(function () {
        $(".contentPane .tabs li").removeClass("active")
        $(this).addClass("active")
    })
    // CSS dropdown from <select> element
	// var isShift = false;
	// if(typeof(LLedit) === "undefined"){
	    // $("select").each(function (i) {
	
	        // var $ul = $("<ul/>").addClass("droplist").hide()
	        // var $sel = $(this)
	        // $sel.addClass("hide")
	        // $("option", this).each(function (j) {
	            // var $opt = $(this)
	            // $ul.append($("<li/>").text($opt.text())
								// .click(function () { //.attr("tabindex", $sel.attr("tabindex"))
								    // $sel.val($opt.val());
									// window.scrollTo(0,0)
								    // $("li", $ul).removeClass("selected")
								    // $(this).addClass("selected");
								    // $("span.selected", $ul.parent()).text($(this).text())
								    // $ul.hide()
								    // $ul.parent().css({ "z-index": 0 })
								    // return false;
								// })
								// .focusin(function () {
								    // $sel.val($opt.val());
								    // $("span.selected", $ul.parent()).text($(this).text())
	
								// })
								// .hover(function () {
								    // $(this).toggleClass("hover");
								// })
						// )
	
	        // })
	        // // fix for incorrect event bubbling in ie
	        // $(document).click(function (e) {
	            // if ((e.target.className.indexOf("selected") + e.target.className.indexOf("btn")) != -1) {
	                // $(".select ul").hide()
					// isShift = false
	            // }
	        // })
	        // //write selected option <span> into the DOM
	        // var $wrap = $("<span/>")
							// .addClass("select")
							// .attr("tabindex", $sel.attr("tabindex"))
							// .append($("<span/>")
								// .addClass("selected")
								// .text($sel.find(":selected").text())
							// )
							// .append($("<span/>")
								// .addClass("btn")
								// .hover(function () {
								    // $(this).toggleClass("hover")
								// })
								// .click(function (e) {
								    // e.preventDefault();
								    // $(this).prev(".selected").click();
								// })
							// )
							// .click(function () {
							// $(".contentPane .inner").css({position:"inherit"})
							    // $(".select ul").hide().parent().css({ "z-index": 0 });
							    // $ul.show();
							    // $(this).css({ "z-index": 50 })
							// })
	
							// .blur(function () {
								// isShift =false;
							    // $ul.hide()
								// $(".contentPane .inner").css({position:"relative"})
							    // $ul.parent().css({ "z-index": 0 })
							    // return false;
							// })
							// .focusin(function (e) {
							    // e.preventDefault();
							    // var selIndex = ($sel.find(":selected").index() + 1)
							    // var lastchar = ""
							    // $(this).keydown(function (e) {
							        // e.preventDefault();
									// isShift = e.shiftKey;
										// // handle arrow and alphanumeric keys
										// switch (e.keyCode) {
											// case 9:
											// if(isShift){
												// $(this).prev().prev("label").focus()}
											// else{
												// $(this).next("input").focus()};
												// break;
											// case 38:
		
												// $("li:eq(" + (selIndex -= 1) + ")", this).click();
		
												// break;
											// case 40:
												// $("li:eq(" + (selIndex += 1) + ")", this).click();
		
												// break;
		
											// //case 39: console.log('right'); break;  
											// //case 37: console.log('left'); break;  
											// default:
												// var C = String.fromCharCode(e.keyCode).toUpperCase();
												// var matchEnd = false
												// $("li", this).each(function () {
													// if ($(this).text().indexOf(C) === 0) {
														// //matched first time
														// if (lastchar != C || matchEnd == true) {
															// lastchar = C
															// $(this).click()
														// //    console.log("1st")
															// return false;
														// }
														// else {
															// lastchar = C
															// if ($("li.selected", $(this).parent()).next().text().indexOf(C) === 0) {
																// $("li.selected", $(this).parent()).next().click()
																// return false
															// }
															// else {
																// matchEnd = true
																// return false
															// }
														// }
													// }
												// })
											// }
							        // //console.log(C +" "+ lastchar + " "+ matchEnd)
							    // })
	
	
							// })
	        // $sel.after($wrap.append($ul))
			// if(!isIE){
			// $sel.parent().css({"position":"absolute", "padding-bottom":"2em"}).after("<div style=\"height:4em\"></div>")
			// }
    	// })
	// }


})



function checkmaxheight(){
	var maxheight = 0;var boxheight = 0;
	$(".cols").each(function(){
			$(".box",this).each(function(){
				var el= $(this)
				el.css('height','');
				maxheight = (el.height() > maxheight) ? el.height() : maxheight;
			})
			$(".box",this).css('height', maxheight);
				maxheight = 0
	})
	maxheight = 0
	
	$(".tabs ul li").each(function(){
		
		var el= $(this)
		el.css('height','');
		maxheight = (el.height() > maxheight) ? el.height() : maxheight;
	})
	//$(".tabs ul li").css('height', maxheight);
	//$(".tabs ul li a span").css('height', maxheight);
	
}
function gup(name, source) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(source);
    if (results == null) return "";
    else return results[1];
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


