jQuery.fn.highlight = function(pat,tit) {
 function innerHighlight(node, pat, tit) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'keyword-term';
    spannode.setAttribute('title', tit);
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat, tit);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase(), tit);
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.keyword-term").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

function processPage(keywords) {
	var docElements = $("#content .node-body, #content .procedure");	
	$.each(keywords, function(name,value) {
		docElements.highlight(name, value);
	});
}


$(function(){
	
	//sectionsTree
	var sectionOpenId = $.cookie('sectionOpen');
	$('span.procedures-list').not('#'+sectionOpenId).hide();
	
	$('a.email-button').button( { icons: { primary: 'ui-icon-mail-closed'} });
	$('a.register').button( { icons: { primary: 'ui-icon-person'} });
	
	$('#sectionsTree ul').treeshow({
		animated: "slow",
		collapsed: true,
		unique: true,
		persist: "cookie",
		toggle: function() {
			$(this).find('>span h4').toggleClass('state-active');
		}
		
	});
	
	$('#'+sectionOpenId).prev('h4.procedures-toggle').addClass('state-active');
			
	$('#sectionsTree h4').hover(
		function(){
			$(this).addClass('state-hover');	
		},
		function() {
			$(this).removeClass('state-hover');
		}
	);
	
	
	
	
	$('#sectionsTree h4.procedures-toggle').bind('click', function(){
			var thisSectionId = $(this).next('span.procedures-list').attr('id');
			
			if( $('#'+thisSectionId).is(':hidden') ) { 
				$('#sectionsTree h4.procedures-toggle.state-active').removeClass('state-active').next('span.procedures-list').slideUp(); 
				
				$(this).addClass('state-active'); $('#'+thisSectionId).slideDown();
				
				$.cookie('sectionOpen', thisSectionId, { path:Croogo.basePath } );
			}
			
			else {
				
				$(this).removeClass('state-active'); $('#'+thisSectionId).slideUp(); 
				
				$.cookie('sectionOpen', null, { path:Croogo.basePath } );
			}
			
			return false; 
		});
	
		
	$('a.section-info').click(function() {
		
		return false;
	})
	
	$('#sectionsTree').fadeIn('slow');
	$('#lcc').hide();
	//sectionsTree end
	
	
    
    $('.toggle-panel').click(function(){
       var target = '#' + $(this).attr('rel');
       $(target).toggle('slow');
       return false;
    });
    
    //$("#newsflash .container").after('<div id="news-pager">').cycle({
//    	fx:	'scrollLeft',
//    	timeout:7000,
//    	delay: -2000,
//		pager:  '#news-pager'	  
//    	
//    });
    
    $('#rotator').cycle({
		fx:     'fade', 
		speed:   3000, 
		timeout: 3000,
		next:   '#rotator', 
    	pause:   1 
	}); 
	
    $('.slideshow').cycle({
		fx: 'fade',
		timeout: 2500,
        speed:  1500
	});
	$('#pdfCatRotator').cycle({
		fx:     'fade', 
		speed:   3000, 
		timeout: 3000,
		next:   '#pdfCatRotator', 
    	pause:   1 
	}); 
	

    $('#locations-infobox').accordion( {
        autoHeight: false,
        navigation: true
    });
    
//    $('.openPanel').click(function(){
//        var myhref = $(this).attr('href');
//        $("h4 a[href='"+myhref+"']").next('div.address').show();
//        return false;
//    });
    
    $('.xtabs').tabs(
    
    ); 
    
    
	$('.toggler').live('click', function()  
				{
					var ttarget = '#' + $(this).attr('rel');
					$(ttarget).toggle('slow');
					return false;				
				}
			);    
    
    
    $('#genderTabs').tabs({cookie: { path:Croogo.basePath  }}).fadeIn('slow');    
	$('a.female-positions,a.male-positions').css('opacity','0.5');
    
	$('a.female-positions').hover(
		function(){
			$(this).animate({opacity:1}, 200);
			$('#shownFemaleResults').attr('id','').fadeOut();
			$(this).next('div.map-area').attr('id','shownFemaleResults').fadeIn();
		},
		function(){
			$(this).animate({opacity:0.5}, 100);
		}
	
	);
	$('a.male-positions').hover(
		function(){
			$(this).animate({opacity:1}, 200);
			$('#shownMaleResults').attr('id','').fadeOut();
			var maparea = $(this).next('div.map-area');
			$(maparea).attr('id','shownMaleResults').fadeIn();
		},
		function(){
			$(this).animate({opacity:0.5}, 100);
		}
	
	);
	$('a.map-area-close').click(function(){
		var openedarea = $(this).parent('div.map-area');	
		$(openedarea).attr('id','').fadeOut();
		return false;	
	});
		
	$('#map-procedures-nav').removeClass('loader');
    
		
	
	$('#CommentAddForm input,#CommentAddForm textarea,#GftForm input,#GftForm textarea').tipsy({ trigger: 'focus', gravity: 'w' });
	$('.tipsyit').tipsy({ trigger: 'hover', gravity: 'w' });
	//$('a.blog.view').colorbox({innerWidth:760, opacity:0.5, close:"X" });
	
	$('a.mybox').colorbox({ maxWidth:"90%", maxHeight:"90%", scalePhotos:true, close:"X"});
	$('a.youtube-link').colorbox({iframe:true, innerWidth:480, innerHeight:360, close:"X" });

	/* authorize */
	
	// Delete a cookie
	//$.cookie('fauthorize', null);
	$('#openCalc').button({
		            icons: {
		                primary: "ui-icon-calculator"
		            }
			        });
	
	var fauthorized = $.cookie('fauthorize');
	if ( fauthorized != '1') {
		
	var email = $( "#authorizeEmail" ),
		allFields = $( [] ).add( email ),
		tips = $( ".validateTips" );

	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}

	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}
		
		$( "#authorizeDialog" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Login": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );

					//bValid = bValid && checkLength( name, "username", 3, 16 );
					bValid = bValid && checkLength( email, "email", 6, 80 );
					//bValid = bValid && checkLength( password, "password", 5, 16 );

					//bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. yourname@gmail.com" );
					//bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

					if ( bValid ) {
//						console.log('Save '+ email.val() +' to db and continue to destination '+ $('#authorizeDestination').val());
						$.cookie('fauthorize', '1', { expires: 3600, path: Croogo.basePath });
						
						var regman = Croogo.basePath+'clinic/mailings/qaddtorize/e_m:'+email.val();
						$.get(regman, function(){
							
							$( "#authorizeDialog" ).dialog( "close" );
							var authorizeDestination = $('#authorizeDestination').val();
							if (authorizeDestination == '#') {
								$('#cfHolder').fadeIn(500, function(){ $('#cfHolder').removeClass('ui-helper-hidden'); });
							}
							else {
								window.location.href = authorizeDestination;
							}
							
							
						});
						
						
					}
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});

		
		$( ".authorize,#link-27,#openCalc" )
			//.button()
			.click(function() {
				$( "#authorizeDestination" ).attr('value', $(this).attr('href'));
				
				$( "#authorizeDialog" ).dialog( "open" );
				return false;
			});
		
		}
		else {
			
			$('#openCalc').click(function(){
				$('#cfHolder').fadeIn(500, function(){ $('#cfHolder').removeClass('ui-helper-hidden'); });
				return false;
			});
		}

});
