//Navigation
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    $(this).find('ul').parent().addClass('hover');

    var topWidth = $(this).find('ul').parent().width();
    var widthLeft = ((200 - topWidth) / 2) * -1;

    if($(this).find('ul').parent().attr('class') == 'last hover') {
       widthLeft = -120;
    }

    ddmenuitem = $(this).find('ul').css('visibility', 'visible').css('left', widthLeft);
}

function jsddm_close(){ 
	if (ddmenuitem) {
		ddmenuitem.parent().removeClass('hover');
		ddmenuitem.css('visibility', 'hidden'); 
	}
}

function jsddm_timer()
{ closetimer = window.setTimeout(jsddm_close, timeout); }

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

document.onclick = jsddm_close;

//Google maps
function Infowin(latlng, html) {
	this.latlng_ = latlng;
	this.html_ = html;
	this.prototype = new GOverlay();

	// Creates the DIV representing the infowindow
	this.initialize = function(map) {
		var div = $('<div />');
		div.css({
			position : 'absolute',
			width : 306
		}).appendTo(map.getPane(G_MAP_FLOAT_PANE));

		this.map_ = map;
		this.div_ = div;

		this.update(html);
	};

	this.update = function(html){
		this.html_ = html;

		this.div_.empty();

		var content = $('<div/>').addClass('infowin-content').css({
			'position' : 'relative',
			'overflow' : 'hidden',
			'top' : -5
		}).html(html);

		$('<div />').addClass('infowin-container').css({
			'background' : 'url(/images/webimages/infow-top.png) no-repeat',
			height : '21.5em',
			padding: '5px 10px 0 77px'
		}).append(content).appendTo(this.div_);

		$('<div />').css({
			'background' : 'url(/images/webimages/infow-bottom.png) no-repeat top right',
                        width: 251+'px',
                        height:'2em',
			'margin' : '0 10px 0 55px'
		}).appendTo(this.div_);

		this.redraw(true);
	};

	// Remove the main DIV from the map pane
	this.remove = function() {
	  this.div_.remove();
	};

        this.hide = function(){
            this.div_.hide();
        };

        this.show = function(){
            this.div_.show();
        };

        this.visible = function(){
            return this.div_.filter(':visible').length;
        };

	// Copy our data to a new instance
	this.copy = function() {
	  return new Infowin(this.latlng_, this.html_);
	};

	// Redraw based on the current projection and zoom level
	this.redraw = function(force) {
		if (!force) return;

		var point = this.map_.fromLatLngToDivPixel(this.latlng_);

		// Now position our DIV based on the DIV coordinates of our bounds
		this.div_.css({
			left : point.x + (this.div_.width() / 2) - 128,
			top : point.y - (this.div_.height() / 2) - 22
		});

                if(!document.body.filters)
                    return;
                $('div',this.div_).each(function(){
                    var iebg = $(this).css('background-image').split('url("');
                    if(!iebg[1]){
                        return;
                    }
                    iebg = iebg[1].split('")')[0];
                    $(this).css('background-image', 'none').get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+iebg+"',sizingMethod='crop')";
                });
	};
}

//Process directions
function processDirections()
{
    $("#directions").html('');
    var from = $("input[name='postcode']").val();
    var to = $("input[name='coords']").val();
    var location = $("input[name='location']").val();
    var directionsPanel = document.getElementById('directions');
    var directions = new GDirections(map, directionsPanel);
    directions.load('from: '+from+' to: '+to);
    $('#results, #directions').show();
    $('h3.resultsHeading').html('Directions from <span>'+from+'</span>');
}

$(document).ready(function(){	

	//dropdown
	$('#level1 > li').bind('mouseover', jsddm_open);
    $('#level1 > li').bind('mouseout', jsddm_timer);
    
	$('#level1 > li').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	//left nav
	if($("#menuSUBMENU").length)
		$("#menuSUBMENU").addClass("box");
	
	//input boxes
	$('input:text').click(function(event) {
       $(this).attr('value','');
	});
	
	//search for links to youtube
	$('a').each(function(){  
        var href = $(this).attr('href');  
        if (href && href.match(/watch\?v=([a-zA-Z0-9\-_]+)/)){  
            $(this).attr('rel','prettyPhoto');   
        }
    });

     $('blockquote').each(function(){ 
        if($("div",this).length < 1) {
           $(this).children().wrapAll("<div>");
        }
     });

       //setting
       $('img.mask').each(function(){  
          if($(this).parent().children('img').length > 1) {
             $alt = $(this).parent().children('img').attr('alt');
             $(this).attr('alt',$alt);             
          }
       });
	   
	   /*    
			Original
			
	   $('img.mask').each(function(){  
          if($(this).parent().children('img').length > 1) {
             $alt = $(this).parent().children('img').attr('alt');
             $(this).attr('alt',$alt);             
          }
       });
	   
	   next
	   
	          $('img.mask').each(function(){  
          if($(this).parent().children('img').length > 1) {
             $alt = $(this).parent().children('img').attr('alt');
             $(this).attr('alt',$alt);             
          }else if($(this).parent().children('a img').length > 1) {
             $alt = $(this).parent().children('a img').attr('alt');
             $(this).attr('alt',$alt);
			 }
       });
	   
	   
	   */

	   
	   			   //works for the homepage carousel
				   
					   $('img.homemask').each(function(){
						if($(this).parent().children('img').length > 1){
							$alt = $(this).parent().children('img').attr('alt');
							$(this).attr('alt',$alt);  
						}
					   });
					
					$('div.box1a div.box div.featureInfo img.homemask').each(function(){
  							$alt = $('div.box1a div.featureInfo a img#pic1').attr('alt');
							$(this).attr('alt',$alt);
					   });
					
					
					
						$('div.box1b div.featureInfo img.homemask').each(function(){
						if($(this).parent().children('img').length > 1){

  							$alt = $('div.box1b div.featureInfo #pic2').attr('alt');
							$(this).attr('alt',$alt);
							
						}
					   });
					   
					   
					   					
						$('div.box1c div.featureInfo img.homemask').each(function(){
						if($(this).parent().children('img').length > 1){

  							$alt = $('div.box1c div.featureInfo #pic3').attr('alt');
							$(this).attr('alt',$alt);
							
						}
					   });
					   
					   $('div.box1d div.featureInfo img.homemask').each(function(){
						if($(this).parent().children('img').length > 1){
							
  							$alt = $('div.box1d div.featureInfo #pic4').attr('alt');
							$(this).attr('alt',$alt);
							
						}
					   });

	//quote box
	$('#features div.box blockquote').each(function(){  
		if($.trim($(this).text()).length < 2) {
			$(this).parent().parent().parent().remove();
        }
    });
	
	//text box
	$('#features div.box div.featureInfo').each(function(){  
	   if($.trim($(this).text()).length < 2 && ($(this).has('img').length < 1 || $('img',this).hasClass('homemask') == false)) {
	      $(this).parent().parent().remove();
           }
           if($("img",this).length < 2) {
              $("img.mask",this).remove();
           }
        });
	
	//add 1st class if 1st class box removed
	$('#features > div').each(function(i){  
		var currentClass = $(this).attr('class');

		if(i == 0 && currentClass.indexOf('1') == -1) {
			$(this).attr('class', currentClass + '1');
		}
        });
	
	//2 cols
	if($.trim($('#top #topLeft div.box div.leftBox').text()).length < 2 && $('#top #topLeft div.box div.leftBox').has('img').length < 1 && $('#top #topLeft div.box #imageBox').has('img').length < 1) {
           $('#topLeft').remove();
    }
	
	if($.trim($('#top #topRight div.box #quotation blockquote').text()).length < 2) {
		$('#topRight').remove();
    }

	if($('#middle div.box div.leftBox').length && $.trim($('#middle div.box div.leftBox').html()).length < 2 && $('#middle div.box div.rightBox #quotation').length && $.trim($('#middle div.box div.rightBox #quotation').html()).length < 2) {
		$('#middle').remove();
    }
	
	if($.trim($('#bottom #bottomLeft div.box div.left').text()).length < 2 && $('#bottom #bottomLeft div.box div.left').has('img').length < 1 && $.trim($('#bottom #bottomLeft div.box div.right').text()).length < 2 && $('#bottom #bottomLeft div.box div.right').has('img').length < 1 && $.trim($('#bottom #bottomLeft div.box div.link').text()).length < 2 && $('#bottom #bottomLeft div.box div.link').has('img').length < 1) {
		$('#bottomLeft').remove();
    }
		
	if($('#middle div.box .nogallery').length > 0 && $.trim($('#middle div.box .nogallery').text()).length < 2) {
		$('#middle').remove();
    }
		
	if($.trim($('#contentImageBox').text()).length < 2 && $('#contentImageBox').has('img').length < 1) {
		$('#contentImageBox').parent().remove();
    }
	
	//tabs
	if($.trim($('#tab1').text()).length < 2) {
		$('#tabs').remove();
    }
	
	//accordian
	if($.trim($('#accordian li:first > div').text()).length < 2) {
		$('#accordian').remove();
    }
	
	$('#accordian > li div').each(function(i){  
		if($.trim($(this).text()).length < 2 && $(this).has('img').length < 1) {
			$(this).parent().remove();
        }	
    });
	
	//banner overlay
	if($('#banner #overlay').length && $.trim($('#banner #overlay').text()).length < 2) {
		$('#overlay').remove();
    }
	
	//banner
	if($.trim($('#banner').text()).length < 2 && $('#banner').has('img').length < 1) {
		$('#banner').remove();
    }

	//sidebar quote box
	$('#sidebar div.box blockquote').each(function(){  
		if($.trim($(this).text()).length < 2) {
			$(this).parent().parent().remove();
        }
    });
	
	
	//featureInfoSideCol
	$('#sidebar div.box .featureInfoSideCol').each(function(){  
		if($(this).text().length < 2 && $(this).has('img').length < 1 && $(this).parent().has('img').length < 1) {
			$(this).parent().parent().remove();
        }
    });

	//sidebar downloads
	if($.trim($('#downloads').text()).length < 2) {
		$('#downloads').parent().remove();
    }
	
	//sidebar related links
	if($.trim($('#relatedLinks').text()).length < 2) {
		$('#relatedLinks').parent().remove();
    }
	
	//sidebar content box
	$('#sidebar div.box div.featureInfo').each(function(){  
		if($.trim($(this).text()).length < 2 && $('img',this).length < 2) {
			$(this).parent().remove();
        }
    });
	
	$('ul.linkSet li a, #tabs ul li a').each(function(){ 
		var str = $(this).text();	
		$(this).html(str);
	});
		
	
	//gallery
	if($('div.scrolling img').length > 0) {
		
		if($('div.scrolling ul').length < 1) {
			$('div.scrolling img').wrapAll("<ul>");
			$('div.scrolling img').wrap("<li>");
			
			$('div.scrolling img').each(function(){  
				var src = $(this).attr('src').replace('.height-95','');
				$(this).attr('height','96');
		        var a = $('<a/>').attr('href', src).attr('rel','prettyPhoto[gallery1]');
		        $(this).wrap(a);
			});
		}
                else if($('.containerprofiles li p').length < 1) {                 
                   $('div.scrolling img').each(function(){  

                      if($(this).parent("a").length == 1) {
                          var src = $(this).attr('src');
                          $(this).attr('height','96').attr('rel','prettyPhoto[gallery1]');
                          
                          if($(this).parent('a[href*="Profile"]').length > 0) {

                          }
                          else {  
                             $(this).parent("a").attr("href",src).attr('rel','prettyPhoto[gallery1]');
                          }
                      }
                      else {
                         var src = $(this).attr('src');
                         $(this).attr('height','96').attr('rel','prettyPhoto[gallery1]');
                         var a = $('<a/>').attr('href', src).attr('rel','prettyPhoto[gallery1]');
		         $(this).wrap(a);
                      }
                   });
                }
		//gallery scroller
		if($('.containerprofiles').length) {
			$('.scrolling').serialScroll({
				items:'li',
				prev:'#buttons a.prev',
				next:'#buttons a.next',
				offset:0,
				start:0,
				duration:600,
				step:4,
				force:true,
				stop:true,
				lock:false,
				cycle:true,
				jump: false
			});
		}
		else {
			$('.scrolling').serialScroll({
				items:'li',
				prev:'#buttons a.prev',
				next:'#buttons a.next',
				offset:0,
				start:0,
				duration:800,
				force:true,
				stop:true,
				lock:false,
				cycle:true,
				jump: false
			});
		}
		
		$galleryTitle = $('div.nogallery').text();
		$('div.scrolling ul li:empty').remove();
		$('div.nogallery').remove();
		
		$('div.gallery p.title').append($galleryTitle + ' ('+$('div.scrolling img').length+')');
	}
	else if ($('div.gallery').length) {
		$('div.gallery').remove();
	}
	
	if($('#bottom #bottomRight div.box .nogallery').length > 0 && $.trim($('#bottom #bottomRight div.box .nogallery').text()).length < 2) {
		$('#bottomRight').remove();
	}
	
	if($("a[rel^='prettyPhoto']").length)
		$("a[rel^='prettyPhoto']").prettyPhoto({theme:'light_rounded'});

	//last class on li
	$("#level1 > li:last, ul.underline li:last, .featureInfo ul li:last, #rightMenu ul li ul li:last, div.documents div.downloadbody:last").addClass("last");	
	
	//a-z
	if($('div.listby-alphabet').length) {
		$('.ListByselectedLetter').wrap('<a/>');
		
		$('div.listby-alphabet a').wrapAll('<ul id="searchAlphabet"/>');
		$('div.listby-alphabet a').wrap('<li/>');
		
		$('div.listby-alphabet a span.ListByselectedLetter').parent().parent().addClass('alphaSelected');
		
		$('div.listBy-page').wrapAll('<div id="results"/>');
		
		$('#results').wrapAll('<div id="searchBoxAndResults" class="gradientOutline" />');
		
		$selectedLetter = $('span.ListByselectedLetter').text();
		
		$('#results').prepend('<p class="titleAZ">'+$selectedLetter+'</p>');
		
	}
	
	//add roundies    
        if(document.domain.indexOf('sheffield') > -1) {
	   DD_roundies.addRule('.box, .listby-alphabet', '5px');
           DD_roundies.addRule('#features .box, div.formTable', '8px');
	}

	if($.browser.msie && $.browser.version < 7) {	   
           DD_roundies.addRule('.gradientOutline, #skSearchResultsWrapper, .homemask, .mask');
        }	

	//accordian
	if ($("#accordian").length && $(".SKEditorWrapper").length == 0){
		$("#accordian").accordion({ autoHeight: false });	
	}
	
	//tabs
	if ($("#tabs").length){
		$('#tabs').tabs();
	}
	
	//qtip
	if($("#contentBlock span").length && $("#contentBlock span").attr("title").length)
	{
		$("#contentBlock span").hover(
			function () {
			
			 	var $title = $(this).attr("title");
			 	$(this).attr("atitle",$title);
				$('[title]').removeAttr('title');
	
				$(this).qtip({
		            content: {
		                text: $title
		            },
		            show: {
		                solo: true,
		                ready: true
		            },
		            hide: {
		                fixed: true
		            },
		            style: {
		                name: 'light',
		                tip: 'bottomLeft',
		                border: {
		                    radius: 2,
		                    color: '#0e69b0'
		                }
		            },
		            position: {
		                corner:{
		                    target: 'center',
		                    tooltip: 'bottomLeft'
		                }
		            }
		        });
				},
				function () {
					var $title = $(this).attr("atitle");
					$(this).attr("title",$title);
					$('[title]').removeAttr('atitle');
					
				  	$("#contentBlock span").qtip("destroy"); 
				}
				
				
		);
	}
	
	//homepage slider
	if ($("#slider ul#rotate").length){
		$bannerFeatures = $('#slider ul#rotate li');
	    $bannerNav = $('#slider ol#controls li');
	    $bannerNavButtons = $('#slider ol#controls li a');
	
	    var options = {
	         'slideType':'fade',
	         'fadeInOut':true,
	         slideChange : function (currentSlideIndex) {
	             $bannerNav.removeClass('on');
	             $bannerNav.eq(currentSlideIndex).addClass('on');
	         }
	     };
	
	    $bannerNavButtons.click(function(event) {
	         var clickIndex = $bannerNavButtons.index(this);
	         $bannerFeatures.dumbCrossFade('jump',clickIndex, options);
	         event.preventDefault();
	    });
	    $bannerFeatures.dumbCrossFade(options);
	   
	}
	
	//search results
	if($(".searchInputOuter").length) {
		$(".searchInputOuter").each(function(i) {
			$(this).addClass("input_"+i);
	    });
	}
	
	if($("#skSearchResultsWrapper").length)
		$("#skSearchResultsWrapper").prepend("<h2 class='searchSubTitle'>Search results for '"+$(".searchforinput").attr("value")+"'</h2>");
	
	//form
	if($("#contentBlock form").length) {
		$("#contentBlock form").addClass("niceform");
		
		$('select').each(function(){  
			$(this).attr('size','1');
	    });
		
	}
	
	//login
	if($(".extranetLoginForm").length) {
		//$.getScript("/scripts/niceForms.js");
	}
	
	/*	if($("#innerContentWrapper form").length){
			$("#innerContentWrapper form").addClass("niceform");
			$(".extranetLoginForm").addClass("formElement");
			$("div.extranetLoginInputRow").addClass("formTextbox");
			$("div.extranetLoginInputRowText").addClass("FormContentLeft");
			$(".extranetLoginInputRowInput").addClass("FormContentRight");
	}*/
	
        //documents
        if($(".documents").length) {
           var header = $("#innerContentWrapper h1").text();
           $("#folder").attr('value',header );
        }

	//google maps
	if($('#map_canvas').length){
	   

	   $("#results").hide();
           var address = $('#address').html();
           var addressgeo = $('#addressgeo').text();
           var latlongcoords = $.trim($('#latlongcoords').text());
           var location;

           $('#address, #addressgeo, #latlongcoords').remove();

           map = new GMap2(document.getElementById('map_canvas'));

           geocoder = new GClientGeocoder();

           if(latlongcoords.length > 0) {
              location = latlongcoords;
           }
           else {
              location = addressgeo;
           }

           location = $.trim(location );

           geocoder.getLatLng(
              location,
              function(point) {
                 map.setCenter(point,15);
                 map.setUIToDefault();                    

                 var html =  "<h2>Location</h2>"+
                    address+
		    "<h2>Get directions to here</h2>"+
		    "<p>Enter your postcode in the field below to display directions<br/><br/></p>"+
		    '<form action="" method=""><input type="text" class="text" name="postcode" /><input type="hidden" name="location" value="Sheffield Children\'s NHS Foundation Trust" /><input type="hidden" name="coords" value="'+point+'" /><a href="javascript:processDirections();"><img src="/images/webimages/search_button.png"/></a></form>';

                 // Define info window using Infowin class and assign it to the map
                 var info = new Infowin(point, html);
                 map.addOverlay(info);

                 // Icon definitions for the markers
                 var greenIcon = new GIcon(G_DEFAULT_ICON);
                 greenIcon.image = "/images/webimages/green_marker.png";
                 greenIcon.shadow = "/images/webimages/shadow_marker.png";
                 greenIcon.iconSize = new GSize(26,30);
                 greenIcon.shadowSize = new GSize(26,30);

                 // Example marker definitions
                 var greenMarker = new GMarker(point, {icon: greenIcon});
                 map.addOverlay(greenMarker);

                 // Example closing/opening of info window when clicking on marker
                 GEvent.addListener(greenMarker, 'click', function(){
                    if(info.visible())
                       info.hide();
                    else
                       info.show();
                 });
              }
           );

       // Function to allow proper focuing of form elements in info windows
       $('#map_canvas form input').live('click',function(){
           $(this).focus();
       });

   }


});

$(window).load(function(){
        //equal heights
	if($(".featureInfo").length > 1)
		$(".featureInfo").equalHeights();

	if($("#top .box").length > 1)
		$("#top .box").equalHeights();
	
	if($("#middle .box").length > 1)
		$("#middle .box").equalHeights();
	
	if($("#bottom .box").length > 1)
		$("#bottom .box").equalHeights();

        $('div.link').each(function(){
           if($(this).parent('.box') && $(this).parent().parent('#sidebar').length < 1 && $(this).parent().parent().parent('#sidebar').length < 1) {
              $(this).addClass('boxbottom');
           }
        });
});
