$(document).ready(function(){
	$("#icon-home").addClass("current_page_item");
	$current_index = $('.current_page_item').index();
	
	$('#menu-icon li').hover(
		function(){
			$('#menu-icon li a').addClass('hover');
		},
		function(){
			$('#menu-icon li a').removeClass('hover');
		}
	);
        
        
    if ($(".widget_categories li").length%2 != 0) {
        $(".widget_categories ul").append("<li><a>&nbsp;</a></li>");
    }
    
    if ($(".widget_tag_cloud a").length%2 != 0) {
        $(".widget_tag_cloud").append("<a>&nbsp;</a>");
    }
	    
    var base             = rooturl2,
        $mainContent     = $("#outerWrapper"),
        $ajaxSpinner     = $("#ajax-loader"),
        $searchInput     = $("#s"),
        $allLinks        = $("a"),
        $el,
        $newHeight,
        $current_index = 0,
        $clicked_index = 0,
		$fbAppIds = '257075984307407',
        $current_page,
        $mediaload;
        

    $('a:urlInternal').live('click', function(e) { 
            $el = $(this);
	
            $current_index = $('.current_page_item').index();
            $clicked_index = $el.parent().index();

            if ((!$el.hasClass("comment-reply-link")) && ($el.attr("id") != 'cancel-comment-reply-link')) { 		
                    var path = $(this).attr('href').replace(base, '');
                    $.address.value(path);
                    $(".current_page_item").removeClass("current_page_item");
                    $allLinks.removeClass("current_link");
                    $el.addClass("current_link").parent().addClass("current_page_item");
                    return false;
            }
			if($(this).attr('target') != '_blank'){	
				
            // Default action (go to link) prevented for comment-related links (which use onclick attributes)
            	e.preventDefault();
            }
    });  

    $('#searchform').submit(function() {  
            var s = $searchInput.val();
            if (s) {
            		s = s.replace(/ /g, '+');
                    var query = '/?s=' + s;
                    $.address.value(query);  
            }
            return false;
    });  
    
    bindTopFeed();
    
    $.address.change(function(event) {
							  
      			//ignore for video subsections                       
    	if (((location.href.indexOf('?video=')>0) && $mediaload) || ($pageChange == 'media')) {
          //media();
          $mediaload = false;
          $pageChange = '';    
          return false;      
        } 				
        //reset
        $mediaload = false;
        $pageChange = '';
    
    		if($($el).attr('target') == '_blank'){
    			window.open($($el).attr('href'), '_blank');
    		}
    		else if($($el).parent('span').hasClass('expand')){
    			//console.log($($el).parent('span').hasClass('expand'));
    		}
    		else if(!$($el).parent('span').hasClass('expand')){
				
				if (event.value) {
					if (($('#contentWrapper').attr('class')=='news') && ($el) && ($($el.parent().parent()[0]).attr("id")=="news-nav")) {
					//if ($('#contentWrapper').attr('class')=='news') {	
					  getNewsWithoutTransition(event);
					} else if (($('#contentWrapper').attr('class')=='concepts') && ($el) && ($($el.parent().parent()[0]).attr("class")=="concept-scroll")) {
						//$('.concept-left').fadeOut();
						$('.concept-left').hide("slide", { direction: "left" }, 1000);
						getConceptWithoutTransition(event);
					} else {					
					  if($clicked_index > $current_index){
							$mainContent.animate({marginLeft: -960,opacity: 0},500,function(){
								$mainContent.css({'margin-left':960});
								$mainContent.empty().load(base + event.value + ' #contentWrapper', function(response, status) {
                   //create jquery object from the response html
                   var $response=$(response);
                   var new_title = $response.filter('title').text();                   
								    changeWebtitle(new_title);                                	  
                    if (status == 'error') {
                	     generatePageNotFound();	     
                	  } else {								
											if($('#contentWrapper').attr('class') == 'home'){
												$('.menu-live').css({'opacity':0});
											}
											else{
												$('.menu-live').css({'opacity':1});
											}
											//home page
											if($('#contentWrapper').attr('class') == 'home'){
												$('.header-menu-lines').attr('id','icon-line-page-home');
												$('#contentWrapper').css({opacity:1});
												$('#icon-home').addClass('current_page_item');
												$('#icon-home').find('a').addClass('current_link');
												home();
											} else if($('#contentWrapper').attr('class') == 'about-us'){
												
												$('.header-menu-lines').attr('id','icon-line-page-about');
												$('#header-linkabout').addClass('current_page_item');
												$('#header-linkabout').find('a').addClass('current_link');
												aboutus();
											}
											//news page
											else if($('#contentWrapper').attr('class') == 'news'){
												$('.header-menu-lines').attr('id','icon-line-page-news');
												$('#header-linknews').addClass('current_page_item');
												$('#header-linknews').find('a').addClass('current_link');											
												news();
											}
											//services page
											else if($('#contentWrapper').attr('class') == 'consultants'){
												$(".current_page_item").removeClass("current_page_item");
												$('#menu-icons .icon-our-consultants').addClass('current_page_item');
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-consultants');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-consultants');
												}
												$('#header-linkservices').addClass('current_page_item');
												$('#header-linkservices').find('a').addClass('current_link');
												consultants();
											}
											//contact us page
											else if($('#contentWrapper').attr('class') == 'contact-us'){
												$('.header-menu-lines').attr('id','icon-line-page-contact-us');
												$('#header-linkcontact').addClass('current_page_item');
												$('#header-linkcontact').find('a').addClass('current_link');
												contactUsForm();
											}
											else if($('#contentWrapper').attr('class') == 'work-with-us'){
												$('.header-menu-lines').attr('id','icon-line-page-work-with-us');
												$('#header-linkwork').addClass('current_page_item');
												$('#header-linkwork').find('a').addClass('current_link');
												workWithUs();
											}
											//work with us details
											else if($('#contentWrapper').attr('class') == 'work-with-us-details'){
												$('.header-menu-lines').attr('id','icon-line-page-work-with-us');
												$('#header-linkwork').addClass('current_page_item');
												$('#header-linkwork').find('a').addClass('current_link');
												workDetails();
											}
											else if($('#contentWrapper').attr('class') == 'expertise'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-expertise');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-expertise');
												}
												$('#header-linkmethodology').addClass('current_page_item');
												$('#header-linkmethodology').find('a').addClass('current_link');
												expertise();
											}
											else if($('#contentWrapper').attr('class') == 'concepts'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-concepts');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-concepts');
												}
												$('#header-linkportfolio').addClass('current_page_item');
												$('#header-linkportfolio').find('a').addClass('current_link');
												concepts();
											}
											else if($('#contentWrapper').attr('class') == 'articles'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-articles');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-articles');
												}
												$('#header-linkclient').addClass('current_page_item');
												$('#header-linkclient').find('a').addClass('current_link');
												articles();
											}
											else if($('#contentWrapper').attr('class') == 'media'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-media');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-media');
												}
												$('#header-linkmedia').addClass('current_page_item');
												$('#header-linkmedia').find('a').addClass('current_link');
												media();
											}
											else if($('#contentWrapper').attr('class') == 'events'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-events');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-events');
												}
												$('#header-linkcasestudy').addClass('current_page_item');
												$('#header-linkcasestudy').find('a').addClass('current_link');
												events();
											}
											else if(($('#contentWrapper').attr('class') == 'blog') || ($('#contentWrapper').attr('class') == 'tag')){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-blog');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-blog');
												}
												$('#header-linkapproach').addClass('current_page_item');
												$('#header-linkapproach').find('a').addClass('current_link');
												blog();
											}
											// client page
											else if($('#contentWrapper').attr('class') == 'clients'){
												$('.header-menu-lines').attr('id','icon-line-page-clients');
												$('#header-linkclients').addClass('current_page_item');
												$('#header-linkclients').find('a').addClass('current_link');											
											   clients();
											}
											// partners page
											else if($('#contentWrapper').attr('class') == 'partners'){
												$('.header-menu-lines').attr('id','icon-line-page-partners');
												$('#header-linkpartners').addClass('current_page_item');
												$('#header-linkpartners').find('a').addClass('current_link');											
											   partners();
											}
										  // services page
										  else if($('#contentWrapper').attr('class') == 'services'){                  		                  																												
										  		if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-services');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-services');
												}
												$('#header-linkservices').addClass('current_page_item');
												$('#header-linkservices').find('a').addClass('current_link');                    											
												services();                  		                      											   
											} 
										  // sitemap page
										  else if($('#contentWrapper').attr('class') == 'sitemap'){                  		                  											                    											
												sitemap();                  		                      											   
											} 
                      											
											} // else  
											$ajaxSpinner.fadeOut();
											$mainContent.animate({marginLeft: '0', opacity: 1},500, function(){
												
											});
											stButtons.locateElements();
											
									}); 
	
							});
							
						} 
						else{						
							$mainContent.animate({marginLeft: 960,opacity: 0},500,function(){
								$mainContent.css({'margin-left':-960});
								$mainContent.empty().load(base + event.value + ' #contentWrapper', function(response, status) {   								    
                   //create jquery object from the response html
                   var $response=$(response);
                   var new_title = $response.filter('title').text();                   
								    changeWebtitle(new_title);								    
                	  if (status == 'error') {
                	     generatePageNotFound();	     
                	  } else {
                    								
											if($('#contentWrapper').attr('class') == 'home'){
												$('.menu-live').css({'opacity':0});
											}
											else{
												$('.menu-live').css({'opacity':1});
											}
											//home page
											if($('#contentWrapper').attr('class') == 'home'){
												$('.header-menu-lines').attr('id','icon-line-page-home');
												$('#contentWrapper').css({opacity:1});
												$('#icon-home').addClass('current_page_item');
												$('#icon-home').find('a').addClass('current_link');
												home();
											}
											else if($('#contentWrapper').attr('class') == 'about-us'){
												$('.header-menu-lines').attr('id','icon-line-page-about');
												$('#header-linkabout').addClass('current_page_item');
												$('#header-linkabout').find('a').addClass('current_link');
                        aboutus();							
											}
											//news page
											else if($('#contentWrapper').attr('class') == 'news'){
												$('.header-menu-lines').attr('id','icon-line-page-news');
												$('#header-linknews').addClass('current_page_item');
												$('#header-linknews').find('a').addClass('current_link');
												news();
											}
											//services page
											else if($('#contentWrapper').attr('class') == 'consultants'){
												$(".current_page_item").removeClass("current_page_item");
												$('#menu-icons .icon-our-consultants').addClass('current_page_item');
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-consultants');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-consultants');
												}
												$('#header-linkservices').addClass('current_page_item');
												$('#header-linkservices').find('a').addClass('current_link');
												consultants();
											}
											//contact us page
											else if($('#contentWrapper').attr('class') == 'contact-us'){
												$('.header-menu-lines').attr('id','icon-line-page-contact-us');
												$('#header-linkcontact').addClass('current_page_item');
												$('#header-linkcontact').find('a').addClass('current_link');
												contactUsForm();
											}
											else if($('#contentWrapper').attr('class') == 'work-with-us'){
												$('.header-menu-lines').attr('id','icon-line-page-work-with-us');
												$('#header-linkwork').addClass('current_page_item');
												$('#header-linkwork').find('a').addClass('current_link');
												workWithUs();
											}
											//work with us details
											else if($('#contentWrapper').attr('class') == 'work-with-us-details'){
												$('.header-menu-lines').attr('id','icon-line-page-work-with-us');
												$('#header-linkwork').addClass('current_page_item');
												$('#header-linkwork').find('a').addClass('current_link');
												workDetails();
											}
											else if($('#contentWrapper').attr('class') == 'expertise'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-expertise');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-expertise');
												}
												$('#header-linkmethodology').addClass('current_page_item');
												$('#header-linkmethodology').find('a').addClass('current_link');
												expertise();
											}
											else if($('#contentWrapper').attr('class') == 'concepts'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-concepts');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-concepts');
												}
												$('#header-linkportfolio').addClass('current_page_item');
												$('#header-linkportfolio').find('a').addClass('current_link');
												concepts();
											}
											else if($('#contentWrapper').attr('class') == 'articles'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-articles');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-articles');
												}
												$('#header-linkclient').addClass('current_page_item');
												$('#header-linkclient').find('a').addClass('current_link');
												articles();
											}
											else if($('#contentWrapper').attr('class') == 'media'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-media');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-media');
												}
												$('#header-linkmedia').addClass('current_page_item');
												$('#header-linkmedia').find('a').addClass('current_link');
												media();
											}
											else if($('#contentWrapper').attr('class') == 'events'){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-events');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-events');
												}
												$('#header-linkcasestudy').addClass('current_page_item');
												$('#header-linkcasestudy').find('a').addClass('current_link');
												events();
											}
											else if(($('#contentWrapper').attr('class') == 'blog') || ($('#contentWrapper').attr('class') == 'tag')){
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-blog');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-blog');
												}
												$('#header-linkapproach').addClass('current_page_item');
												$('#header-linkapproach').find('a').addClass('current_link');
												blog();
											}	
											// client page
											else if($('#contentWrapper').attr('class') == 'clients'){
												$('.header-menu-lines').attr('id','icon-line-page-clients');
												$('#header-linkclients').addClass('current_page_item');
												$('#header-linkclients').find('a').addClass('current_link');											
											   clients();
											}
											// partners page
											else if($('#contentWrapper').attr('class') == 'partners'){
												$('.header-menu-lines').attr('id','icon-line-page-partners');
												$('#header-linkpartners').addClass('current_page_item');
												$('#header-linkpartners').find('a').addClass('current_link');											
											   partners();
											}
										   	// services page
										  	else if($('#contentWrapper').attr('class') == 'services'){                  		                  																												
												if($('#menu-icons').css('display') == 'block'){
													$('.header-menu-lines').attr('id','icon-line-page-services');
												}
												else{
													$('.header-menu-lines').attr('id','text-line-page-services');
												}
												$('#header-linkservices').addClass('current_page_item');
												$('#header-linkservices').find('a').addClass('current_link');                    											
												services();                  		                      											   
											} 											
										  	// sitemap page
										  	else if($('#contentWrapper').attr('class') == 'sitemap'){                  		                  											                    											
												sitemap();                  		                      											   
											} 
																
										  }//else 404                    										
											$ajaxSpinner.fadeOut();
											$mainContent.animate({marginLeft: '0', opacity: 1},500, function(){
												
											});
											
											stButtons.locateElements();
									}); 
	
							});
						}
						$ajaxSpinner.fadeIn();
						//alert($clicked_index +' = '+ $current_index);
						//if($('#contentWrapper').attr('class') == 'home'){
						//if($current_index == 0) {
						  //$('#shslideshow_1 .slides').cycle('destroy'); // destroy the homepage slide
						//}
					}					
				}
        
            } 

            var current = location.protocol + '//' + location.hostname + location.pathname;
            if (base + '/' != current) {
                    var diff = current.replace(base, '');
                		var xURL = location.search; // added by fritz for $_GET val
                		location = base + '/#' + diff + '' + xURL;          
            }             
    }); // address

    function generatePageNotFound(){
      var pagenotfound = '<div class="content"><div class="content-titlearea"><h1 class="tit">404 Error</h1></div><div class="inner-content-wrapper"><h2>Page not Found</h2></div></div>'
      $('#container').html(pagenotfound);
    } // generatePageNotFound()
      
    function bindTopFeed(){
    	//Top Live Feed
		$('.menu-live').click(function(){
			if($('#page-live-feeds').css('display') == 'block'){
				$('#page-live-feeds').hide();
			}
			else{
				$('#page-live-feeds').show();
				getLatestRssFeeds('page-feed');
			}
							 
		});
	}
    
    function home(){
      $('#shslideshow_1 .slides').cycle('stop'); // destroy the homepage slide
    	var scrollHf = function(){
			if($('#home-feed').length > 0){
				var current = $("#home-feed").css("margin-top").substring(0, $("#home-feed").css("margin-top").length - 2); 
				
				$("#home-feed").css("margin-top", (current - 1) + "px");
				
				if (current <= ($("#home-feed").height() * -1 )) {
					$("#home-feed").css("margin-top", "0px");	
				}
			}
		}
		
		$.ajax({url: rooturltemp+"/php/live.php", success: function(response) {
			$("#home-feed").html(response);
			$jScroller.add("#home-feedcontainer","#home-feed","up",2,true);
	   		$jScroller.start();
			//var intervalHf = setInterval(scrollHf, 100);
		}});  
		    var oneLoops = false;
		    var slideActive = 0;		   
        var slideTimer = 0; 
        var mainSliderOptions = {
        effect: "slideInRight", 
        animSpeed: 500,
        pauseTime: 4000,
        startSlide: slideActive,
        directionNav: true,
        directionNavHide: false,
        controlNav: true,
        controlNavThumbs: false,
        keyboardNav: false,
        pauseOnHover: true,
        manualAdvance: false,
        afterChange: function(){ 
          slideActive = parseInt($('.nivo-controlNav .active').attr('rel'));                 
          if (slideActive == 0 ) {          
            $('#shslideshow_1 .slides').data('nivo:vars').stop = true; //Stop the Slider                 
            slideTimer = setTimeout(function(){ 
              if (slideActive == 0 ) {           
               $('#shslideshow_1 .slides').data('nivo:vars').stop = false; //Start the Slider                              
              }                       
            },10000);
          } else {
            $('#shslideshow_1 .slides').data('nivo:vars').stop = false; //Start the Slider
            clearTimeout(slideTimer);
            slideTimer = 0;            
          } 
        },
        afterLoad: function(){                   
            $('#shslideshow_1 .slides').data('nivo:vars').stop = true; //Stop the Slider                 
            slideTimer = setTimeout(function(){            
             $('#shslideshow_1 .slides').data('nivo:vars').stop = false; //Start the Slider                                    
            },10000); 
        },        
        slideshowEnd: function(){ oneLoops = true; }
        };
      $('#shslideshow_1 .slides').nivoSlider(mainSliderOptions);
      /*  
      $('#shslideshow_1 .slides').cycle({
      activePagerClass: 'activeSlideHome',
      fx: "scrollHorz",
      random:0,  			
      pause:1,
			containerResize: 0, 
			randomizeEffects:0,
			fastOnEvent:0, fit:1,
			speed: 2000,timeout: 2000,
			pager: "#shslideshow_nav_1",
			pauseOnPagerHover: 1,
      after: function(curr, next, opts) {        
        //alert(opts.currSlide);
        var toslide = opts.currSlide; 
        $("#shslideshow_nav_1 a").removeClass('activeSlide');
        $("#shslideshow_nav_1 a:eq("+toslide+")").addClass('activeSlide');
      }      			
		});*/ 
        //process slides
		jQuery("#blog-list").cycle({
      fx: "scrollHorz", cleartypeNoBg: true,          
      before: function(curr, next, opts) {
      opts.animOut.opacity = 0;
      },
      random:0,  			
      pause:1,
			containerResize: 0, 
			randomizeEffects:0,
			fastOnEvent:0, fit:1,
			speed: 1000,timeout: 0,
			next: "#b-next", prev: "#b-prev", pager: "#blognavigationcircle"
		}); 
		
		/*$(".home-bottom .eventholder a").hover(function() {
        if ($(this).find('.up-event-title').css("display") == "none") {
                $(this).find('.up-event-title').show("slide", {direction: "down", mode: "show"}, 300);
        }
        },
        function() {
        if ($(this).find('.up-event-title').css("display") == "block") {
                $(this).find('.up-event-title').hide("slide", {direction: "down", mode: "hide"}, 300);
        }
        });*/
    }  // home
    function getConceptWithoutTransition(event){
	  $clicked_url = base + event.value;
		$('.concept-content').load(base + event.value + ' .concept-left', function() {
		stButtons.locateElements();																				   
		showShareIcons($clicked_url, 400);
		$('.concept-left').show("slide", { direction: "right" }, 1000);
		var current = location.protocol + '//' + location.hostname + location.pathname;
			if (base + '/' != $clicked_url) {
					var diff = $clicked_url.replace(base, '');
					location = base + '/#' + diff;             
			} 
		});
		
	} //getConceptWithoutTransition
	
    function getNewsWithoutTransition(event){
	  $("#news-nav-container #news-nav li a").removeClass('current');
	  $('#news-nav-icon-container #icon-links').animate({opacity:0, marginRight:'-500px'},500);
	  $('#slideShowContainer').fadeOut(500, function() {
	  	$('#ajax-loader').fadeIn();
		 $('#slideShowContainer').empty().html('');
		 $('#slideShowContainer').fadeIn('fast');
		 $('.news #news-wrapper #content').load(base + event.value + ' .news #news-wrapper #slideShowContainer', function(response, status, xhr) {
			$('#ajax-loader').fadeOut();
		  $current_page = $('#contentWrapper').attr('class');
		  if($current_page == 'news'){			  
				var $result=$(response);
				$('#news-nav-icon-container').html($result.find('#news-nav-icon-container').html());
			  	news();			  			  			                   			  			 	   			  			  			    				   
			    animateIconLinks();
			    stButtons.locateElements();
		  }
		});
	  });
	} //getConceptWithoutTransition
	
	function animateIconLinks() {
	  $('#news-nav-icon-container #icon-links').animate({opacity:1, marginRight:'0px'},1000);
	}
	
	function goToNews(index) {
	  $('#slideShowContainer').cycle(index);
	}
    
    function news(){
		$('.header-menu-lines').attr('id','icon-line-page-news');
		$('#header-linknews').addClass('current_page_item');
		$('#header-linknews').find('a').addClass('current_link');    
    $('#news-nav-icon-container #icon-links').css({'opacity':1,'margin-right':'0px'});
		firstCycle = true;
		$('#news-left').hide();
		$('#news-right').hide();
		var startSlide = parseInt($('#news-nav-icon li a.current').parent().index());				
    	startSlide = (startSlide && startSlide>=0) ? startSlide : 0; 			
		$('#slideShowContainer').cycle({
			fx:    'scrollHorz', 
			timeout: 0,  cleartypeNoBg: true,
			startingSlide: startSlide,
			next:  '#news-right img.next', 
			prev:  '#news-left  img.prev',
			before: onBefore,    
			after:  onAfter
		});
		
		$('#news-nav li').each(function(){
			if($(this).find('a').attr('title') == '2007'){
				$(this).hide();
			}
		});
		
                
  		$("#news-nav-container #news-nav li a").click(function(){
  			$("#news-nav-container #news-nav li a").removeClass('current_link');
  			$(this).addClass('current_link');
  		});
        
		var y_current = $('#news-nav-icon').attr('rel');         	
        $("#news-nav-container #news-nav li a[title='"+y_current+"']").addClass('current_link');
		
        if(!$('#news-nav-container #news-nav li a').hasClass('current_link')){
        	
		}
		  
  		if($('#content').hasClass('details')){
  			$('#slideShowContainer').cycle($('#slideShowContainer .current').index());
  		}
		
  		showShareIcons($("ul#news-nav-icon li").find("a.current").attr("url"), 230); // call social shares
      	
    	$('#news-nav-icon li a').click(function(){
    		$('#slideShowContainer').cycle($(this).parent('li').index());
    	});
    	
    	if($('.eventspostSlideHolder').length > 0){
    		contentVerticalScroll();
    	}
    	                                           
    }// news
    
    function onBefore(curr, next, opts) {
      
      opts.animOut.opacity = 0;          	 
	  $('#slideShowContainer').css('overflow', 'hidden');
	}
	
	function onAfter(curr, next, opts) {
    var index = opts.currSlide;
	  /*if (firstCycle) { 
		index = 0;
		firstCycle = false;
	  }*/
	 var cIcons = opts.currSlide + 1; 
	  $("#news-nav-icon li a.current").removeClass('current');
	  $('#news-nav-icon li a[name="'+index+'"]').addClass('current');
	  		
	  $('#slideShowContainer').css('overflow', 'visible');
	  $h = $('#slideShowContainer .news-cycle:eq('+opts.currSlide+')').find('.news-main').height();
	  if($h > 413){
	  	$('#content').css('height',$h);
	  }
	  else{
	  	$('#content').css('height','413');
	  }
	  //showShareButtons(opts.currSlide);
	  showShareIcons($($("ul#news-nav-icon li")[opts.currSlide]).find("a").attr("url"), 230);
	  navigationshows(opts);
	  
	}
	function navigationshows(opts){
	  // hide navigation if first/last added by fritz 07-28-2011	  
			if (opts.slideCount == 1) {
				// hide all
				$('#news-left').hide();
				$('#news-right').hide();			
      }else if ((opts.currSlide +1) == 1) {					
				// hide the prev
				$('#news-left').hide();
				$('#news-right').show();
			} else if ((opts.currSlide +1) == opts.slideCount) {
				// hide the next
				$('#news-left').show();
				$('#news-right').hide();				
			} else {
				$('#news-left').show();
				$('#news-right').show();						
			}  
  }         
  
  function showShareIcons(pagelink, width) { // added by fritz 09/06 make it useful hehehe   152245024845578
  		if($('.share-toolbar').length > 0){     
        FB.init({appId: $fbAppIds, status: true, cookie: true, xfbml: true});      		
  			(function(d){
  			  var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
  			  js = d.createElement('script'); js.id = id; js.async = true;
  			  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
  			  d.getElementsByTagName('head')[0].appendChild(js);
  			}(document));						                                                        
  			//$('.share-toolbar #like').html('<script src="http://connect.facebook.net/en_US/all.js#appId='+$fbAppIds+'&amp;xfbml=1"></script><div class="fb-like" data-href="'+pagelink+'" data-send="false" data-width="'+width+'" data-show-faces="true" data-colorscheme="dark"></div>');                
        //$('#gplus').html('<g:plusone size="standard" href="'+pagelink+'"></g:plusone>');
        gapi.plusone.go();
        //$('#gplus').html('<div id="gplusicon"><g:plusone size="standard" href="'+pagelink+'"></g:plusone></div>');
        var g_param = {"href":pagelink, "size": "standard", "width": 70};
        //gapi.plusone.render("gplusicon",{"href":pagelink, "size": "standard", "width": 70});      
      }  
  }
  
	function showShareButtons(currSlide){
		FB.init({appId: $fbAppIds, status: true, cookie: true, xfbml: true});
		$('.share-toolbar #like').html('<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="'+$($("ul#news-nav-icon li")[currSlide]).find("a").attr("url")+'" send="true" width="150px" layout="button_count" show_faces="false" font=""></fb:like>');
		//$('.share-toolbar #like').html('<script src="http://connect.facebook.net/en_US/all.js#appId=180611585322066&amp;xfbml=1"></script><fb:like href="'+$($("ul#news-nav-icon li")[currSlide]).find("a").attr("url")+'" send="false" width="300" show_faces="false" font=""></fb:like>');
	}
    
    function contactUsForm(){
		$("label").inFieldLabels(); //Fade in and out on focus
		$('img.ajax-loader').remove();
		$('.wpcf7-form').append('<p class="msg"></p>');
		$('.wpcf7-form input.wpcf7-submit').parent('p').append('<div id="contact-loader"></div>');
        $("form").submit(function() {
            var valid = new Array(4);
            for (var i = valid.length-1; i >= 0; -- i) valid[i] = 0;

            if (!$("#username").val()) {
              $("label[for='username']").text("Please enter your name");
              $("label[for='username']").addClass("contact-form-error");
            }else{
               $("label[for='username']").text("Your name");
               $("label[for='username']").removeClass("contact-form-error");
               valid[0] = 1;
            }
            
            if (!$("#email").val()) {
              $("label[for='email']").text("Please enter your email");
              $("label[for='email']").addClass("contact-form-error");
            }else if (($("#email").val()).indexOf("@")<0 || ($("#email").val()).indexOf(".")<0) {
              $("#email").val('');
              $("#email").blur();
              $("label[for='email']").text("Please enter a valid email");
              $("label[for='email']").addClass("contact-form-error");
            }else{
               $("label[for='email']").text("Your email");
               $("label[for='email']").removeClass("contact-form-error");
               valid[1] = 1;
            }
            
            if (!$("#subject").val()) {
              $("label[for='subject']").text("Please enter your subject");
              $("label[for='subject']").addClass("contact-form-error");
            }else{
               $("label[for='subject']").text("Subject");
               $("label[for='subject']").removeClass("contact-form-error");
               valid[2] = 1;
            }
            
            if (!$("#message").val()) {
              $("label[for='message']").text("Please enter your message");
              $("label[for='message']").addClass("contact-form-error");
            }else{
               $("label[for='message']").text("Message");
               $("label[for='message']").removeClass("contact-form-error");
               valid[3] = 1;
            }
            
            
            
            if(valid[0] && valid[1] && valid[2] && valid[3]){
            	$('.wpcf7-form #contact-loader').show();
            	
            	$('.wpcf7-form .msg').html('');
				$data = 'username='+$('#username').val()+'&email='+$('#email').val()+'&subject='+$('#subject').val()+'&message='+$('#message').val();
				$.ajax({
					type: 'POST',
					url: rooturltemp + '/phpgmailer/sendmail.php',
					data: $data,
					success: function(data){						
						if(data == 'true'){
							$('.wpcf7-form #contact-loader').hide();
							$('.wpcf7-form .msg').html('Thank you for your enquiries, we will respond within 3 business days.').show();
						}else if(data == 'false'){		
							$('.wpcf7-form #contact-loader').hide();
							$('.wpcf7-form .msg').html('Could not send your email. Please try again').show();
						}
					}
				});
              return false;
            }else{
              return false;  
            }
        });
    }
    function changeWebtitle(title){
      if (title) {
        document.title = title;
      } else {
        document.title = webname+', '+$('.posttitle').html();
      }
    }
    function consultants(){      		  		  
      //$('.consultant-pic img').removeAttr('title');		  
    	$('.consultants-scroll').css({'opacity':0,'visibility':'hidden'});
    	$('.consultantholder').css({'z-index':1});
    	if($('.fblikesend').length > 0){
    		FB.init({appId: $fbAppIds, status: true, cookie: true, xfbml: true});
			$('.fblikesend').empty();
			$('.fblikesend').empty().html('<script src="http://connect.facebook.net/en_US/all.js#appId=152245024845578&amp;xfbml=1"></script><fb:like href="" layout="button_count" send="true" width="250" show_faces="false" font=""></fb:like>');
        }
        
        $('.consultants-content li .consultant-bottom h4 a').click(function(){
        	$(this).parents('li').find('.consultants-scroll').height($(this).parents('.consultantholder').height());
        	$(this).parents('li').find('.consultants-scroll').width($(this).parents('.consultantholder').width());
        	$(this).parents('.consultantholder').css({'opacity':0,'z-index':0});
        	$scroll_text = $(this).parents('li').find('.consultants-scroll');
        	$($scroll_text).css({'opacity':1,'visibility':'visible'});
        	$($scroll_text).tinyscrollbar();
        	return false;
        });
        
        $('.consultants-scroll .close').click(function(){
        	$(this).parent('.consultants-scroll').css({'opacity':0,'visibility':'hidden'});
        	$(this).parents('li').find('.consultantholder').css({'opacity':1,'z-index':1});
        	
        });
    /*    
		$('.consultant-pic').hover(function(){
			var ids = $(this).attr('id');				
			$('#prev'+ids).slideDown();
		}, function(){
			var ids = $(this).attr('id');				
			$('#prev'+ids).slideUp();		
		});*/
    }
    
    function expertise(){
    	$('.expertiselist li h4 a').click(function(e){
    		$.scrollTo($(this).attr('href'),500);
    		e.preventDefault();
    	});
    	
    	$('.side-nav li a').click(function(e){
    		$.scrollTo($(this).attr('href'),500);
    		e.preventDefault();
    	});
    	
    	$('.side-nav .top').click(function(){
    		$.scrollTo(0, 500);
    	});
    	
    	$('.bottom-content:last').css('border','none');
    	
    	$(window).scroll(function(){
    		$scroll = $(window).scrollTop();
    		if($scroll > 570){
    			$('.side-nav').css({'position':'fixed', 'top':'50px'});
    		}
    		else{
    			$('.side-nav').css({'position':'relative', 'top':'0'});
    		}
    	});
    	
    	$('.bottom-content .boxes ul li a').fancybox({
			'hideOnContentClick': true,
			'centerOnScroll': true
		});
    	
    	$('.bottom-content .boxes ul li a').click(function(e){
    		return false;
    	});
    }
    
    function previewConcept(str){      
  		var ids = str.replace("-150x150", "");    		
  		$('.concept-large-thumb img').attr('src', str);    
    }
	function concepts() {

		var options = {  
				zoomType: 'innerzoom',  
				lens:true,  
				preloadImages: true,  
				alwaysOn:false, 
				xOffset:10,  
				yOffset:0,
				showEffect:'fadein',
				hideEffect:'fadeout',
				title: false
		};
		$('.concept-left').hide();
		$('.concept-left:first').show().addClass('current');   
		$(".concept-right .concept-scroll").cycle({
  			fx:"scrollBothWays",  cleartypeNoBg: true,
  			speed: 1000,
  			timeout: 0, 
  			slideResize:0,
  			next: "#down .next", 
  			prev: "#up .prev",
			after:  conceptsnavigationshows,
			before: function(curr, next, opts) {
			opts.animOut.opacity = 0;
			}
  		});
  		 //$('.concept-content .current a.zoom').jqzoom(options);
  		 //$('.concept-content .current a.zoom').lightBox({captionPosition:'gallery'});
    		$cur_url = '';
    		if($('.concept-left').css('display') == 'block'){
    			$cur_url = $('.concept-left').attr('url');
    		}
        showShareIcons($cur_url, 400);        
        /*
        $('.concept-list a').click(function(){
        	$('.concept-left').removeClass('current');
        	$clicked = $(this).attr('class');
        	$('.concept-left').hide();
        	$('.concept-content #'+$clicked).addClass('current').show();
        	FB.init({appId: "180611585322066", status: true, cookie: true, xfbml: true});
			$('.share-toolbar #like').html('<script src="http://connect.facebook.net/en_US/all.js#appId=180611585322066&amp;xfbml=1"></script><fb:like href="'+$(this).attr('href')+'" send="true" width="350" show_faces="false" font=""></fb:like>');
			$('.concept-content .current a.zoom').jqzoom(options);
        	return false;
        });*/
        
		
		function conceptsnavigationshows(curr, next, opts){
			// hide navigation if first/last added by fritz 07-28-2011
			$('.concept-scroll').attr('id', opts.currSlide);
			// hide navigation if first/last added by fritz 07-28-2011	
			var index = opts.currSlide;
			
			$('#up .prev')[index == 0 ? 'fadeOut' : 'fadeIn']();			
			$('#down .next')[index == opts.slideCount - 1 ? 'fadeOut' : 'fadeIn']();			      	  
	  } 		
   		   
  } //concepts
    function aboutus() {
      $('#aboutfullview').jqm(); //Modal dialog box            
      $('#viewfullview').click(function(){
				$('#aboutfullview').jqmShow();
				$('#aboutfullview').jqmAddClose('#closeaboutfullview'); 
        //$('#closeaboutfullview').click(function(){}); 				        
      });
    }  
    function clients(){
      
      $(".current_page_item").removeClass("current_page_item");
      $allLinks.removeClass("current_link");
      $("#icon-clients a").addClass("current_link").parent().addClass("current_page_item");
          
  		$(".client-cycle").cycle({     
  			fx:"scrollHorz",
  			timeout: 0, cleartypeNoBg: true, 
  			before: function(curr, next, opts) {
  			opts.animOut.opacity = 0;
  			},			
        pager:"#page-nav-dots",
        after: function(curr,next,opts){    
          var index = opts.slideCount;
          $('#page-nav-dots')[opts.slideCount <= 1 ? 'hide' : 'show']();			          
        }
    	}); // end slides     
      /* 
    	$('ul.client-list li').hover(function(){        
        $('.client_details').hide();
        $('#'+$(this).attr('id')+'-details').show();
      },function(){        
        $('#'+$(this).attr('id')+'-details').hide();
      });
      
      $("#foo").mousedown( function() { // on mousedown
       $(this).css("background-color", intialState ? "#0F0" : "#F00"); // toggle bgColor
       initialState = !initialState; // toggle flag
     });
     */
      
    }//clients()
    
    function partners(){
      
      $(".current_page_item").removeClass("current_page_item");      
      $allLinks.removeClass("current_link");
      $("#icon-partners a").addClass("current_link").parent().addClass("current_page_item");
      
    	$('#backtotop span').click(function() {
    		$('body,html').animate({scrollTop:0},800);
    	});       
          
    	$(window).scroll(function() {
    		if($(this).scrollTop() != 0) {
    			$('#backtotop').fadeIn();	
    		} else {
    			$('#backtotop').fadeOut();
    		}
    	}); 
      /*
      function goToByScroll(id){
      	$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
      }*/ 
                     
    }// partners()
    
    function services() {
    	var service_title = '';
    	var activeService = '';
    	var serviceHover = false;  
      var checkHover = '';       	
    	//hover the title     
      $('.services-list').mouseenter(function() {
      		service_title =  $(this).attr("id"); // name of service
      		activeService = $('#detail-' + service_title); // element Menu
      		activeService.attr('rel', 'serviceActive'); // add active service for displaying
      		$(this).attr('rel', 'serviceActiveMenu'); // add active menu // for hiding
      		activeService.fadeIn();	
      }).mouseleave(function() {
          setTimeout(function() {
              //alert(' -- '+ serviceHover +' -- ');
            if(!serviceHover) {
            //if($('#detail-' + service_title).attr('rel') == 'serviceActive') {
        			$('.services-list').attr('rel', '');
        			$('.service-detail').attr('rel', '');	
        			$('.service-detail').fadeOut('fast');            
            }                
          }, 100); 
      });        
    	// hover the content
      $('.service-detail .content').hover(
        function (){
           serviceHover = true;
        },
        function (){
          serviceHover = false;
    			$('.services-list').attr('rel', '');
    			$('.service-detail').attr('rel', '');	
    			$('.service-detail').fadeOut('fast');        
        }
      );                         
                   
    } //services()
    
    function sitemap(){
      $('#page_entries').masonry({
        columnWidth: 25
      });         
    } //sitemap()
        
    function articles(){
    	if($('.share-toolbar').length > 0){
    		$cur_url = '';
    		if($('.entry').attr('url')){
    			$cur_url = $('.entry').attr('url');
    		}
    		FB.init({appId: $fbAppIds, status: true, cookie: true, xfbml: true});
			$('.share-toolbar #like').html('<script src="http://connect.facebook.net/en_US/all.js#appId=180611585322066&amp;xfbml=1"></script><fb:like href="'+$cur_url+'" send="true" width="350" show_faces="false" font=""></fb:like>');
    	}
    }
    
    function events(){
    	if($('#contentWrapper .eventsHolder').hasClass('detail')){
    		$('.postHolder').hide();
    		$('.postHolder:first').show();
    	}
  		// get link to be share
      $cur_url = '';
  		if($('.entry').attr('url')){
  			$cur_url = $('.entry').attr('url');
  		}
    	showShareIcons($cur_url, 320);
    	if($('#events-list .item').length == 1){
    		$('.actions').css({'opacity':0});
    	}
		$('#actions-up a.prev').hide();
		$('#actions-down a.next').hide();	    	
    	var perslide = 3;								   
  	 
		$(".vertical").cycle({     
			fx:"scrollBothWays",  cleartypeNoBg: true,
			before: function(curr, next, opts) {
			opts.animOut.opacity = 0;
			},			
			after: function (curr,next,opts) {				
			// hide navigation if first/last added by fritz 07-28-2011	
			var index = opts.currSlide;
			
			$('#actions-up a.prev')[index == 0 ? 'hide' : 'show']();			
			$('#actions-down a.next')[index == opts.slideCount - 1 ? 'hide' : 'show']();			
			}, 			
			
			speed: 1000,timeout: 0, slideResize:0,
			next: "#actions-down a.next", prev: "#actions-up a.prev"
  		}); // end slides
  		
      
      //event page click image
      
      var curr_slide = 0;
      var curr_cycle = 0;
      var t_row = 4;                                      
      var thumb_count = parseInt($("#event-slider-thumbnail").attr('rel')); 
      var slide_count = Math.ceil((thumb_count) / t_row);
      $('#event-full-slider').jqm();
      $('.event-slide img, #event-moreslides span').live('click',function(event){
          // setup default slide first
          curr_slide = parseInt($(this).parent().attr('rel'));
          curr_cycle = (curr_slide < t_row) ? 0 : 1;                                                  
          var slidenow = $("#e_thumb_"+curr_slide+" img");                    
          e_loadSlide();            
          $('#event-full-slider').jqmShow();  
                  
          $('#event-slider-thumbnail').cycle('destroy');
      		$("#event-slider-thumbnail").cycle({
            startingSlide: curr_cycle,
            fx: "scrollBothWays", cleartypeNoBg: true,          
            before: function(curr, next, opts) {
            opts.animOut.opacity = 0;
            },
            after: function(curr,next,opts){       
              var index = opts.currSlide;
        			$('#event-thumb-left .prev')[index == 0 ? 'addClass' : 'removeClass']('disabled');			
        			$("#event-thumb-right .next")[index == opts.slideCount - 1 ? 'addClass' : 'removeClass']('disabled');	            		          
            },      
            random:0, containerResize: 0, randomizeEffects:0,
      			fastOnEvent:0, fit:1, speed: 1000,timeout: 0,
      			next: "#event-thumb-right .next", prev: "#event-thumb-left .prev"
      		}); 
          //$('body,html').animate({scrollTop:100},800);  
          event.preventDefault();                                 
      });                  
      // load the lightbox
      //$('#event-slider-thumbnail').delegate('img','click', function(){
      $('#event-slider-thumbnail ul li .e_thumb img').click(function(event){            	
        if(curr_slide != $(this).parent().parent().attr('rel')) {
          curr_slide = $(this).attr('rel');                              
          e_loadSlide($(this));
      	}
      	event.preventDefault();
      });    
      //lightbox image nav click      
      $('#event-slider-left img,#event-slider-right img').click(function(event){
        if($(this).hasClass('disabled')) {//} || (curr_slide < 0) || (curr_slide == $("#event-slider-thumbnail ul:last li:last").attr('rel'))) {
          // can't slide... heheheh
        } else {
          if($(this).hasClass('prev')) {
            var slidecount = parseInt(curr_slide) - 1;           
          } else {            
            var slidecount = parseInt(curr_slide) + 1;
          }               
          // avoid more than slide and negative value heheeh          
          if (slidecount < 0) {
            slidecount = 0;
          } else if (slidecount >= thumb_count) {
            slidecount = thumb_count - 1;
          }                                                 
          curr_slide = slidecount;
          //var slidenow = $("#event-slider-thumbnail ul li[rel='"+curr_slide+"'] .e_thumb img");          
          //var slidenow = $("#e_thumb_"+curr_slide+" img");
          e_loadSlide();  
          //e_goto();
          curr_cycle = parseInt($("#event-slider-thumbnail ul li#"+curr_slide).parent().index());                                  
          curr_cycle = curr_cycle < 0 ? 0 : curr_cycle;
          $('#event-slider-thumbnail').cycle(curr_cycle);                                                                 	        	             
        }   
        //event.preventDefault();            
      }); 
      function e_loadSlide(){           
          $("#event-slider-thumbnail ul > li .e_thumb img").removeClass('aSlide');
          //add active class
          var slidenow = $("li .e_thumb img[rel='"+curr_slide+"']");
          slidenow.addClass('aSlide');
          var viewLarge = slidenow.attr('src').replace('-140x90','');
          // check if the thumbnail is hide          
          $('#largeImage').fadeOut(function(){
              $('#largeImage').attr('src',viewLarge);              
              //$('#large-container').html('<img id="largeImage" src="'+ $('.aSlide').attr('src').replace('-140x90','') +'" style="display: inline;">');     
              $('#largeImage').fadeIn();
              $('#largeImage_desc').html(slidenow.attr('alt'));          
          })            
          e_slide_nav();           
      } //e_loadSlide()             		
      function e_slide_nav(){              
         if (curr_slide == 0) {
            // disable prev
            $('#event-slider-left img').addClass('disabled');
            $('#event-slider-right img').removeClass('disabled');
         } else if(curr_slide >= (thumb_count - 1)) {
            $('#event-slider-left img').removeClass('disabled');
            $('#event-slider-right img').addClass('disabled');         
         } else {
            $('#event-slider-left img').removeClass('disabled');
            $('#event-slider-right img').removeClass('disabled');         
         }
      } //e_slide_nav()
      
    }// events
    
    function blog(){
    	
      //if($('.share-toolbar').length > 0){
    		$cur_url = '';
    		if($('.entry').attr('url')){
    			$cur_url = $('.entry').attr('url');
    		}
    		showShareIcons($cur_url, 400);
    		//FB.init({appId: $fbAppIds, status: true, cookie: true, xfbml: true});
			  //$('.share-toolbar #like').html('<script src="http://connect.facebook.net/en_US/all.js#appId=180611585322066&amp;xfbml=1"></script><fb:like href="'+$cur_url+'" send="true" width="350" show_faces="false" font=""></fb:like>');
    	//}
    	
    	$('.PW_Archives ul.months').hide();
    	$('.PW_Archives li.year a.year-link').click(function(){
    		if(!$(this).parent('li').hasClass('current-year')){
				$('.PW_Archives li.year').removeClass('current-year');
				$('.PW_Archives ul.months').slideUp();
				$(this).parent('li').addClass('current-year');
				$(this).parent('li').find('ul.months').slideDown();
    		}
    	});
    }    
	function media(){           
      var mediaHelperUrl = base+"/wp-content/themes/f5consulting/media_helper.php";
      $mediaload = true; // already load... hehehe      
      //YouTube variables
      var currentVideoId;
      var currentPlaylistId;
      var updateURI = 'media'; // check if what URL will be.. main, categ or direct video
      var updateurlnow = false; // check if url is change already
      var currentDvideo = '';
      $pageChange == 'media';
      var currentClick = '';
            
      $allLinks.removeClass("current_link");
      $('#header-new-linkmedia a').addClass("current_link").parent().addClass("current_page_item");
              
        // set up the media tab navigation
        $('#media-nav-tab .tab').hide();
        $('#media-nav-tab .tab p').hide();
        
		// default opened tab is
		//get page load categ                       
		var media_load = $('#media-nav-tab').attr('class');
		var media_categ = $('#media-nav-tab').attr('rel');
		var media_direct_load = $('#media-video').attr('class');		
		
    currentVideoId = media_direct_load ?  media_direct_load : '';	
		media_categ = (media_categ == 'f5digital-media') ? 'f5digital-creations' : media_categ;
    media_load = media_load ? media_load : 'tv';
    
		
		$('.media-category-active').removeClass('media-category-active');
		$('#media-nav-tab span').removeClass("media-icon-current");
        
    $('#media-nav-tab-'+media_load).show();
		$('.icon-media-'+media_load).addClass("media-icon-current");
		$('#media-nav-tab-'+media_load+' ul li#'+media_categ).addClass("media-category-active");	
		$('p.' + $('#media-nav-tab-'+media_load+' ul li.media-category-active > a').attr('rel')).show();    		          
    currentPlaylist = $('#media-nav-tab-'+media_load+' ul li.media-category-active > a').attr("id").substring(10);  
          
          //Interface variables
          var active = media_load; //"tv";
          var media_load2 = (media_load == 'tv') ? 'radio' : 'tv';
        	var width = 870 - ($('#media-title-'+media_load).width() + $('#media-links-'+media_load).width() + $('#media-title-'+media_load2).width() +15);
        	var collapse = true;
        	var height = 0;
        
        	//YouTube startup
        	updatePlaylist(currentPlaylist);
        	loadUserPlaylists();
        	
        	//Interface startup
        	redrawTitle();
        	
		
      $('.icon-media-tv').click(function(){       	     		            
            var oldClick = currentClick;                             
            if(!checkLoadPage($('#media-nav-tab-tv ul li:nth-child(1)').attr('id'))){
            	return false;
            } else if($(this).hasClass('media-icon-current')) {
              return false;
            }                 
			$('#media-nav-tab .tab p').hide();	
			$('.media-category-active').removeClass('media-category-active');
        	$('#media-nav-tab .tab').hide();
			$('#media-nav-tab-tv').show();
			
			$('#media-nav-tab span').removeClass("media-icon-current");
        	$(this).addClass("media-icon-current");		
			
			$('#media-nav-tab-tv ul li:nth-child(1)').show();
			$('#media-nav-tab-tv ul li:nth-child(1)').addClass("media-category-active");
			$('p.' + $('#media-nav-tab-tv ul li.media-category-active > a').attr('rel')).show();
			
			updateURI = 'category';
			updateURL();
			
			// update playlist			
			// check if the playlist is loaded grrr
			var urlsplit = location.href.split('?');			
			if(oldClick == currentClick) {
				//updateVideo($('#media-related div:first').attr("id").substring(10));
				return false; // bdont load playlist again load 1st video
			} else {
				updatePlaylist($('#media-nav-tab-tv ul li.media-category-active > a').attr("id").substring(10));
			} 									
		});
			
        $('.icon-media-radio').click(function(){  
        	var oldClick = currentClick;
            if(!checkLoadPage($('#media-nav-tab-radio ul li:nth-child(1)').attr('id'))){
            	return false;
            }         
			 	
			$('#media-nav-tab .tab p').hide();								  
			$('.media-category-active').removeClass('media-category-active');								  
        	$('#media-nav-tab .tab').hide();
			$('#media-nav-tab-radio').show();
			
			$('#media-nav-tab span').removeClass("media-icon-current");
        	$(this).addClass("media-icon-current");		
			
			$('#media-nav-tab-radio ul li:nth-child(1)').show();
			$('#media-nav-tab-radio ul li:nth-child(1)').addClass("media-category-active");
			$('p.' + $('#media-nav-tab-radio ul li.media-category-active > a').attr('rel')).show();
			
      updateURI = 'category';
			updateURL();
      			
			// update playlist			
			// check if the playlist is loaded grrr
			var urlsplit = location.href.split('?');			
			if(oldClick == currentClick) {
				//updateVideo($('#media-related div:first').attr("id").substring(10));
				return false; // bdont load playlist again load 1st video
			} else {
				updatePlaylist($('#media-nav-tab-radio ul li.media-category-active > a').attr("id").substring(10));
			} 									
			
		});
		
        $('.icon-media-tv').hover(
        	function(){
				if ($(this).hasClass('media-icon-current'))
				{
					$('#media-nav-tab span').removeClass("media-icon-selected");
					$(this).addClass("media-icon-selected");
				}
        	},
        	function() {
				if ($(this).hasClass('media-icon-current'))
	        		$('#media-nav-tab span').removeClass("media-icon-selected");
        	}
        )
        
        $('.icon-media-radio').hover(
        	function(){
				if ($(this).hasClass('media-icon-current'))
				{
					$('#media-nav-tab span').removeClass("media-icon-selected");
					$(this).addClass("media-icon-selected");
				}
        	},
        	function() {
				if ($(this).hasClass('media-icon-current'))
	        		$('#media-nav-tab span').removeClass("media-icon-selected");
        	}
        )
        
        	        
        	//$('#media-seperator').width(width);
        	//$('#media-links-radio').hide();
        	$('#media-btn-msg').jqm(); //Modal dialog box
        	$("#media-dialog").jqm();
        	
        	if (!isAuthenticated) {
        	    $("#media-commentformarea").hide();
                $("#media-loginlink").show();
            }
            else{
                $("#media-commentformarea").show();
                $("#media-loginlink").hide();
            }
        	
        	//Interface function
        	 function stretchScreen() {
                var dheight = $('html').height();
                var wheight = $(window).height();
        
                // height first header, content, last footer
                var overTop = $("#header-wrapper").height();
                var cbody = $("#content-wrapper").height();
                var overBottom = $("#footer-wrapper").height();
                
                var correct = overTop + overBottom;
                
                if (cbody < dheight || cbody < wheight) {
                    changePush();
                }
                
                if (wheight > dheight) {
                    //$('.b_menuContent').height(cheight);
                }
                
                $(window).bind("resize orientationchange", function() {
                    wheight = $(window).height();
                    noScroll();
                    changePush();
                });
                
                function noScroll() {
                    if (wheight > dheight) {
                        $('html').addClass('html-noscroll');
                    }
                    else if (wheight <= dheight) {
                        $('html').removeClass('html-noscroll');
                    }
                }
                
                function changePush() {
                    if (wheight > dheight) {
                        //$("#content-wrapper").css({ 'min-height' : wheight - correct + 'px' });      
                    }
                    else {
                        //$("#content-wrapper").css({ 'min-height' : dheight - overBottom + 'px' });
                    }
                }
            }
        	
        	//YouTube functions
			function updatePlayListF5Selections(playlistid_list)
			{
        	    f5selectionslists = playlistid_list;
        	    $.ajax({ url: mediaHelperUrl, data: ({f5selections: f5selectionslists}), success: function(response) {
        		    var playlistVideos = $.parseJSON(response);
        		    var playlistHtml = "";
        		    var firstVideo = null; 
        		    
        			$.each(playlistVideos.entry, function(key, value) {
        
        			    if (key == 0) {
        					firstVideo = value;
        			    }
        
        			    var id = value.link[0]["@attributes"]["href"].substring(31, value.link[0]["@attributes"]["href"].indexOf("&"));
        				var thumbnailURL = base+"/wp-content/themes/f5consulting/images/media-loading.gif";
        				
        			    $.ajax({ url: mediaHelperUrl, data: ({videoId: id, action: "playlistVideoDetails"}), success: function(response) {
        				    //Ignore broken videos
        				    if (response.indexOf("thumbnailURL") != -1) {
        				    	var detailInfo = $.parseJSON(response);
        				    	$("#media-vid-" + detailInfo.videoId + " img").attr("src", detailInfo.thumbnailURL[0]);
        
        				    	var duration = "";
        
        						var seconds = parseInt(detailInfo.duration[0]);
        						
        						var hour = Math.floor(seconds / 3600); 
        						if (hour != 0) {
        							duration += hour + ":";
        							seconds -= hour * 3600;
        						}
        					
        						var min = Math.floor(seconds / 60);
        						if (min == 0 && hour == 0) {
        							duration += "0:";
        						}
        						else if (min == 0 && hour > 0) {
        						    duration += "00:";
        						}
        						else {
        							duration += min + ":";
        							seconds -= min * 60;
        						}
        						
        						if (seconds < 10) {
        							duration += "0";	
        						}
        						duration += seconds;
        						
        						$("#media-vid-" + detailInfo.videoId + " .media-length-bg-right").html(duration);
        				    }
        			    }});
        				    
        				playlistHtml += '<div id="media-vid-' + id + '" class="media-item"><a href="javascript:;"><span class="media-thumb"><img width="95" height="55" src="' + thumbnailURL + '" /></span><span class="media-vid-length"><span class="media-length-bg-left"></span><span class="media-length-bg-right">0:00</span><div class="clear"></div></span>' + value.title + '</a></div>';		
        			});
        			
        			$("#media-related").html(playlistHtml);
        
        			updateVideo(firstVideo.link[0]["@attributes"]["href"].substring(31, firstVideo.link[0]["@attributes"]["href"].indexOf("&")));
        
        			$(".media-item").click(function() {         					  
							if(!checkLoadPage($('#media-nav-tab .media-category-active').attr('id') ,$(this).attr("id").substring(10))){
								return false;
							}        	        				         
							updateVideo($(this).attr("id").substring(10));
							updateURI = 'loadvideo';
							currentDvideo = $(this).attr("id").substring(10); 
							updateURL();                                 
        			});
        			
        			$(".media-link").click(function() {
        					var oldClick = currentClick;
							if(!checkLoadPage($(this).parent().attr('id'))){
								return false;
							}        				        			
    						$('.media-category-active').removeClass('media-category-active');
    						$(this).parent().addClass('media-category-active');
    						$('.tab p').hide();
    						$('p.' + $(this).attr('rel') ).show();
			
							updateURI = 'category';
							updateURL();
							// check if the playlist is loaded grrr
							var urlsplit = location.href.split('?');			
							if(oldClick == currentClick) {
								//updateVideo($('#media-related div:first').attr("id").substring(10));
							return false; // bdont load playlist again load 1st video
							} else {
	    						// if this media link is to all f5 selections, load the other playlists
	    						if ($(this).attr('id') == 'media-linkothers')
	    							updatePlayListF5Selections($(this).attr('playlists'));
	    						else
	    	        				updatePlaylist($(this).attr("id").substring(10));
							} 	          						

        			});
        			
        			$('#media-related-container').pajinate({
        				items_per_page : 8,
        				item_container_id : '#media-related'
        			});
        			
        			if($('#media-related-container').find('.page_navigation > .page_link').size() == 1){
        				$('#media-related-container').find('.page_navigation').css ({
        					'display' : 'none'
        				});
        			}
        		}});
			}
			
        	function updatePlaylist(playlistId) {
        	    currentPlaylistId = playlistId;
        	    $.ajax({ url: mediaHelperUrl, data: ({playlistId: currentPlaylistId}), success: function(response) {
        		    var playlistVideos = $.parseJSON(response);
        		    var playlistHtml = "";
        		    var firstVideo = null; 
        		    
        			$.each(playlistVideos.entry, function(key, value) {
        
        			    if (key == 0) {
        					firstVideo = value;
        			    }
        
        			    var id = value.link[0]["@attributes"]["href"].substring(31, value.link[0]["@attributes"]["href"].indexOf("&"));
        				var thumbnailURL = base+"/wp-content/themes/f5consulting/images/media-loading.gif";
        				
        			    $.ajax({ url: mediaHelperUrl, data: ({videoId: id, action: "playlistVideoDetails"}), success: function(response) {
        				    //Ignore broken videos
        				    if (response.indexOf("thumbnailURL") != -1) {
        				    	var detailInfo = $.parseJSON(response);
        				    	$("#media-vid-" + detailInfo.videoId + " img").attr("src", detailInfo.thumbnailURL[0]);
        
        				    	var duration = "";
        
        						var seconds = parseInt(detailInfo.duration[0]);
        						
        						var hour = Math.floor(seconds / 3600); 
        						if (hour != 0) {
        							duration += hour + ":";
        							seconds -= hour * 3600;
        						}
        					
        						var min = Math.floor(seconds / 60);
        						if (min == 0 && hour == 0) {
        							duration += "0:";
        						}
        						else if (min == 0 && hour > 0) {
        						    duration += "00:";
        						}
        						else {
        							duration += min + ":";
        							seconds -= min * 60;
        						}
        						
        						if (seconds < 10) {
        							duration += "0";	
        						}
        						duration += seconds;
        						
        						$("#media-vid-" + detailInfo.videoId + " .media-length-bg-right").html(duration);
        				    }
        			    }});
        				    
        				playlistHtml += '<div id="media-vid-' + id + '" class="media-item"><a href="javascript:;"><span class="media-thumb"><img width="95" height="55" src="' + thumbnailURL + '" /></span><span class="media-vid-length"><span class="media-length-bg-left"></span><span class="media-length-bg-right">0:00</span><div class="clear"></div></span>' + value.title + '</a></div>';		
        			});
        			
        			$("#media-related").html(playlistHtml);
        
        			updateVideo(firstVideo.link[0]["@attributes"]["href"].substring(31, firstVideo.link[0]["@attributes"]["href"].indexOf("&")));
        
        			$(".media-item").click(function() {    
							if(!checkLoadPage($('#media-nav-tab .media-category-active').attr('id') ,$(this).attr("id").substring(10))){
								return false;
							}      	        				                 				         
						updateVideo($(this).attr("id").substring(10));
						updateURI = 'loadvideo';
						currentDvideo = $(this).attr("id").substring(10);
						updateURL();                    				
        			});
        			
        			$(".media-link").click(function() {
        					var oldClick = currentClick;
							if(!checkLoadPage($(this).parent().attr('id'))){
								return false;
							}        	        				
    						$('.media-category-active').removeClass('media-category-active');
    						$(this).parent().addClass('media-category-active');
    						$('.tab p').hide();
    						$('p.' + $(this).attr('rel') ).show();

          			updateURI = 'category';
          			updateURL();
							// check if the playlist is loaded grrr
							var urlsplit = location.href.split('?');			
							if(oldClick == currentClick) {
								//updateVideo($('#media-related div:first').attr("id").substring(10));
							return false; // bdont load playlist again load 1st video
							} else {
	    						// if this media link is to all f5 selections, load the other playlists
	    						if ($(this).attr('id') == 'media-linkothers')
	    							updatePlayListF5Selections($(this).attr('playlists'));
	    						else
	    	        				updatePlaylist($(this).attr("id").substring(10));   									    	        				
							}           						

							
        			});
        			
        			$('#media-related-container').pajinate({
        				items_per_page : 8,
        				item_container_id : '#media-related'
        			});
        			
        			if($('#media-related-container').find('.page_navigation > .page_link').size() == 1){
        				$('#media-related-container').find('.page_navigation').css ({
        					'display' : 'none'
        				});
        			}
        		}});
        	}
          function checkLoadPage(cat, vidID){
          	vidID = vidID ? '?video='+ vidID : '';
            var urlsplit = location.href.split('#');                                        								
			currentClick = cat;
			cat = '/f5digital-media/'+cat+'/';									
			if(urlsplit[1] == cat+''+vidID) {
				return false; // kill you
			} else {
				return true; // go on...
			}                 	
          }//checkLoadPage	
          //bit_url function
          function bit_url(pagelink) { 
            var url=pagelink['url'];
            var username="f5digitaloperations"; // bit.ly username
            var key="R_2a8e89398e5e7463c63e76a84a1dbc1e";
            $.ajax({
            url:"http://api.bit.ly/v3/shorten",
            data:{longUrl:url,apiKey:key,login:username},
            dataType:"jsonp",
            success:function(v)
              {
              var shorten_url=v.data.url; 
              $('#media-btn-sharethis').show();                                           
        			$('#media-btn-sharethis').html('<span class="st_sharethis_button" displayText="ShareThis" st_url="'+shorten_url+'" st_title = "'+pagelink['title']+'" st_image = "'+pagelink['image']+'" st_summary="'+pagelink['excerpt']+'" ></span>');
        			if (stButtons){stButtons.locateElements();} // Parse ShareThis markup
              //return bit_url_now;
              }
            });            
          } //bit_url       	
        	function updateShareThis(pagelink){  
            // make it possible.. grrr
              var shorten_url = encodeURI(pagelink['url']); 
              $('#media-btn-sharethis').show();                                           
        			$('#media-btn-sharethis').html('<span class="st_sharethis_button" displayText="ShareThis" st_url="'+shorten_url+'" st_title = "'+pagelink['title']+'" st_image = "'+pagelink['image']+'" st_summary="'+pagelink['excerpt']+'" ></span>');
        			if (stButtons){stButtons.locateElements();} // Parse ShareThis markup     
            //bit_url(pagelink);                                                      
          } 
        	//add commas http://www.mredkj.com/javascript/numberFormat.html
        	function addCommas(nStr){
        		nStr += '';
        		x = nStr.split('.');
        		x1 = x[0];
        		x2 = x.length > 1 ? '.' + x[1] : '';
        		var rgx = /(\d+)(\d{3})/;
        		while (rgx.test(x1)) {
        			x1 = x1.replace(rgx, '$1' + ',' + '$2');
        		}
        		return x1 + x2;
        	} // END addCommas             
          function updateURL() {
              $mediaload = true;
      				var urlsplit = this.location.href.split('#');
              var newURL = urlsplit[0] + '#/f5digital-media/';
              var category = $('#media-nav-tab .media-category-active').attr('id');
              // update URL      
              if (updateURI == 'category') {
                newURL = newURL+ category + '/';                
              } else if (updateURI == 'loadvideo') {                
                newURL = newURL+ category + '/?video='+ currentDvideo;
              }
              $pageChange = 'media'; 
              this.location.href =  newURL;                                                    				      				      				                      				            
          } //updateURL()       
        	function updateVideo(videoId) {      			
            
            $('#media-btn-sharethis').hide();
                                 	                               	    
            var loadFirst = currentVideoId ? false : true;
            currentVideoId = currentVideoId ? currentVideoId : videoId; 
            var cVideoId = currentVideoId;                                                                                                       
        		$("#media-video").html('<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/' + currentVideoId + '?version=3&feature=player_embedded" width="620" height="380"><param name="movie" value="http://www.youtube.com/v/' + currentVideoId + '?version=3&feature=player_embedded"/><param name="wmode" value="transparent"></object>');
        
        		$("#media-viewCount").html("Loading");
        	    $("#media-likes").html("Loading");
        	    $("#media-commentcount").html("Loading");
        	    $("#media-description").html("Loading");
        	    $("#media-bar-green").css("width", "0px");
        		
        		$.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId}), success: function(response) {
        		    var videoInfo = $.parseJSON(response);
        
        		    var categories = $("#media-link" + currentPlaylistId).html();
        
        		    //$("#media-viewCount").html(videoInfo.viewCount + " views");
        		    $("#media-viewCount").html(addCommas(videoInfo.viewCount) + " views");
        		    $("#media-likes").html((videoInfo.numLikes[0] == null ? "0" : addCommas(videoInfo.numLikes[0])) + " likes, " + (videoInfo.numDislikes[0] == null ? "0" : addCommas(videoInfo.numDislikes[0])) + " dislikes");
        		    $("#media-commentcount").html(videoInfo.commentsCount[0]);
        		    var ydescription = videoInfo.description[0] == null ? 'No description available.' : videoInfo.description[0];
                ydescription = ydescription.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
                  return '<a target="_blank" href="'+url+'">'+url+'</a>';
                });   // old codes
                $('#video-moredetails').removeAttr('style');
                $('.btnshow').removeAttr('style');                
          			var categ = '<p><label>Category: </label>'+videoInfo.category[0]+'</p>';
          			var tags = '<p><label>Tags: </label>'+videoInfo.keywords[0]+'</p>';                
        		    $("#media-description").html(ydescription);
        		    $('#video-moredetails').html(categ +''+ tags);
        		    
        		    $("#media-bar-green").css("width", Math.round(parseInt(videoInfo.rating) / 5 * 120) + "px");

        			// update the sharethis button
              var pagelink = new Array();
      				var urlsplit = location.href.split('#');
              var newURL = urlsplit[0] + '#/f5digital-media/';
              var category = $('#media-nav-tab .media-category-active').attr('id');
                           
              pagelink['url'] = newURL + category + '?video='+ cVideoId;
              pagelink['title'] = videoInfo.title[0] == null ? 'F5 Digital Media.' : videoInfo.title[0];
              pagelink['image'] = videoInfo.thumbnailURL[0] == null ? 'F5Digital Media - '+pagelink['title'] : videoInfo.thumbnailURL[0];
              pagelink['excerpt'] = videoInfo.description[0] == null ? 'F5Digital Media' : videoInfo.description[0]; 
              updateShareThis(pagelink);  
        			
        			$("#media-commentarea").html("Loading");        			
        			updateComments(cVideoId);
        
        			$("#media-commentsubmit").click(function() {
        			    $.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId, action: "addComment", comment: $("#media-commentfield").val() }), success: function(response) {
        					updateComments(currentVideoId);
        		    	}});
        			});
        			
        			$("#media-btn-like").click(function() {
        				if (!isAuthenticated) {
        					$('#media-btn-msg').jqmShow(); 
        				}
        				else{
        					$.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId, action: "addLike" }), success: function(response) {
        						if (response.indexOf("true") != -1) {
        							$.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId}), success: function(response) {
        								var videoInfo = $.parseJSON(response);
        	
        								$("#media-likes").html((videoInfo.numLikes == null ? "0" : videoInfo.numLikes) + " likes, " + (videoInfo.numDislikes == null ? "0" : videoInfo.numDislikes) + " dislikes");
        								$("#media-bar-green").css("width", Math.round(parseInt(videoInfo.rating) / 5 * 120) + "px");
        							}});
        						}
        						else {
        						    $("#media-dialog").jqmShow();
        					        $("#media-dialogtext").html("Sorry, we could not add your like for this video.");
        						}
        					}});
        				}
        			});
        
        			$("#media-btn-dislike").click(function() {
        				if (!isAuthenticated) {
        					$('#media-btn-msg').jqmShow();
        				}
        				else{
        			   
        			    $.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId, action: "addDislike" }), success: function(response) {
        				    if (response.indexOf("true") != -1) {
        				        $.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId}), success: function(response) {
        						    var videoInfo = $.parseJSON(response);
        
        						    $("#media-likes").html((videoInfo.numLikes == null ? "0" : videoInfo.numLikes) + " likes, " + (videoInfo.numDislikes == null ? "0" : videoInfo.numDislikes) + " dislikes");
        						    $("#media-bar-green").css("width", Math.round(parseInt(videoInfo.rating) / 5 * 120) + "px");
        				        }});
        					}
        				    else {
        					    $("#media-dialog").jqmShow();
        				        $("#media-dialogtext").html("Sorry, we could not add your dislike for this video.");
        					}
        		    	}});
        				}
        			});        			
        		}});
            currentVideoId = '';
        	} //updateVideo
        
        	function updateComments(currentVideoId) {
        	
        	    $.ajax({ url: mediaHelperUrl, data: ({videoId: currentVideoId, action: "comments"}), success: function(response) {
        	        var commentHtml = "";
        	        
        			//Ignore broken videos
        		    if (response.indexOf("content") != -1) {
        		        var commentInfo = $.parseJSON(response);
        
                    var c_count = 0;
        		        if (commentInfo.entry.content != null) {
        					//Siingle comment
        		            var friendlyDate = '';
        					var postDate = new Date();
        					
        					postDate.setUTCFullYear(commentInfo.entry.published.substring(0, 4));
        					postDate.setUTCMonth(parseInt(commentInfo.entry.published.substring(5, 7)) - 1);
        					postDate.setUTCDate(commentInfo.entry.published.substring(8, 10));
        					postDate.setUTCHours(commentInfo.entry.published.substring(11, 13));
        					postDate.setUTCMinutes(commentInfo.entry.published.substring(14, 16));
        					postDate.setUTCSeconds(commentInfo.entry.published.substring(17, 19));
        					
        					var dateDiff = Math.round(((new Date()).getTime() - postDate.getTime()) / 1000);
        				    
        				    if (dateDiff < 3600) {
        				        dateDiff = Math.floor(dateDiff / 60);
        				        friendlyDate = dateDiff + ' minute' + (dateDiff > 1 ? 's' : '') + ' ago';
        				    }
        				    else if (dateDiff < 86400) {
        				        dateDiff = Math.floor(dateDiff / 3600);
        				        friendlyDate = dateDiff + ' hour' + (dateDiff > 1 ? 's' : '') + ' ago';
        				    }
        				    else if (dateDiff < 604800) {
        				        dateDiff = Math.floor(dateDiff / 86400);
        				        friendlyDate = dateDiff + ' day' + (dateDiff > 1 ? 's' : '') + ' ago';
        				    }
        				    else {
        				        dateDiff = Math.floor(dateDiff / 604800);
        				        friendlyDate = dateDiff + ' week' + (dateDiff > 1 ? 's' : '') + ' ago';
        				    }
        				    
        		        	commentHtml += '<div class="media-comment-box"><p>' + commentInfo.entry.content + '</p><p><a href=http://youtube.com/user/' + commentInfo.entry.author.name + '>' + commentInfo.entry.author.name + '</a><span class="media-time"> ' + friendlyDate + '</span></p></div>'
        		          c_count++;
                    }
        		        else { 
        			        //Multiple comments
        			        $.each(commentInfo.entry, function(key, value) {
        						var friendlyDate = '';
        						var postDate = new Date();
        						
        						postDate.setUTCFullYear(value.published.substring(0, 4));
        						postDate.setUTCMonth(parseInt(value.published.substring(5, 7)) - 1);
        						postDate.setUTCDate(value.published.substring(8, 10));
        						postDate.setUTCHours(value.published.substring(11, 13));
        						postDate.setUTCMinutes(value.published.substring(14, 16));
        						postDate.setUTCSeconds(value.published.substring(17, 19));
        						
        						var dateDiff = Math.round(((new Date()).getTime() - postDate.getTime()) / 1000);
        					    
        					    if (dateDiff < 3600) {
        					        dateDiff = Math.floor(dateDiff / 60);
        					        friendlyDate = dateDiff + ' minute' + (dateDiff > 1 ? 's' : '') + ' ago';
        					    }
        					    else if (dateDiff < 86400) {
        					        dateDiff = Math.floor(dateDiff / 3600);
        					        friendlyDate = dateDiff + ' hour' + (dateDiff > 1 ? 's' : '') + ' ago';
        					    }
        					    else if (dateDiff < 604800) {
        					        dateDiff = Math.floor(dateDiff / 86400);
        					        friendlyDate = dateDiff + ' day' + (dateDiff > 1 ? 's' : '') + ' ago';
        					    }
        					    else {
        					        dateDiff = Math.floor(dateDiff / 604800);
        					        friendlyDate = dateDiff + ' week' + (dateDiff > 1 ? 's' : '') + ' ago';
        					    }
        					    
        			        	commentHtml += '<div class="media-comment-box"><p>' + value.content + '</p><p><a href="http://youtube.com/user/' + value.author.name + '">' + value.author.name + '</a><span class="media-time"> ' + friendlyDate + '</span></p></div>'
        			        	c_count++;
        			        });
        		        }
        			}                                    
                  $('#media-comments-all')[(c_count > 10) ? 'fadeIn' : 'fadeOut']();
        	        $("#media-commentarea").html(commentHtml);
                  $('#media-comments-all').click(function() {
                        $('.media-comment-box').slideDown('slow');
                  });
        	        stretchScreen();
        		}});
        	}
        
        	function loadUserPlaylists() {
        		if (isAuthenticated) {
            		$.ajax({ url: mediaHelperUrl, data: ({action: 'getUserPlaylists', username: currentUsername}), success: function(response) {
        				//Populate add this menu
                		var playlists = $.parseJSON(response);
            			var playlistHtml = "";
            		    
            			$.each(playlists.entry, function(key, value) {
            			    playlistHtml += '<li id="media-add-' + value.id.substring(value.id.lastIndexOf("/") + 1) + '">' + value.title + '</li>';
            			});
            
            			playlistHtml += '<li id="media-add-newplaylist">Add Playlist..</li>';
            			$("#media-add-list").html(playlistHtml);
        
            			$("#media-add-list li").click(function() {
        					if ($(this).attr("id") == "media-add-newplaylist") {
        						$("#media-dialog").jqmShow();
        					    $("#media-dialogtext").html("<label id=\"media-add-newlabel\" for=\"media-add-newfield\">Name: </label><input id=\"media-add-newfield\" type=\"text\" />");
        					    $("#media-add-newfield").css("color", "#000000");
        					    
        					    $(window).keypress(function(e) {
        						    if ($("#media-add-newfield").length == 1) {
            							if (e.keyCode == 13 && $("#media-add-newfield").val().trim().length > 0) {
            							    $("#media-add-newfield").css("color", "#000000");
        
            							    $.ajax({ url: mediaHelperUrl, data: ({action: 'addToNewPlaylist', videoId: currentVideoId, playlistName: $("#media-add-newfield").val().trim(), username: currentUsername}), success: function(response) {
                							    
                							    
            								    if (response.indexOf("true") != -1) {
            								        $("#media-dialog").jqmShow();
            								        $("#media-dialogtext").html("You have successfully added this video to your playlist.");
        
            								        loadUserPlaylists();
            								    }
            								    else {
            								        $("#media-dialog").jqmShow();
            								        $("#media-dialogtext").html("Sorry, we could not add this video to your playlist.");
            								    }
            							    }});
            							}
            							else if (e.keyCode == 13) {
            							    $("#media-add-newfield").val("Please enter a playlist name.");
            							    $("#media-add-newfield").css("color", "#ee4444");
                						}
        						    }
        						});
        					}
        					else {
        						$.ajax({ url: mediaHelperUrl, data: ({action: 'addToPlaylist', videoId: currentVideoId, playlistId: $(this).attr("id").substring(10) }), success: function(response) {
        						    if (response.indexOf("true") != -1) {
        						        $("#media-dialog").jqmShow();
        						        $("#media-dialogtext").html("You have successfully added this video to your playlist.");
        						    }
        						    else {
        						        $("#media-dialog").jqmShow();
        						        $("#media-dialogtext").html("Sorry, we could not add this video to your playlist.");
        						    }
        					    }});
        					}
            			});
            		}});
        		}
        	}
        
        	//Interface functions
        	$('#media-title-radio').click(function(){
        		if(active !='radio'){
        			$('#media-links-tv').hide('slide', {direction: 'left'}, 1000, function(){
        				$('#media-seperator').animate({
        					'width':'hide'
        				}, 'slow', function(){
        					$('#media-links-radio').show('slide', {direction: 'left'}, 1000);
        				});
        			});		
        			active = 'radio';
        			$('#media-title-radio').removeClass('media-title');
        			$('#media-title-radio').addClass('media-title-active');
        			$('#media-title-tv').addClass('media-title');                                                                                               
					updatePlaylist($('ul#media-links-radio li:first a').attr('id').substring(10)); // added by fritz 08-09-2011 *** load the first video subcategory   
        		}
        	});
        	
        	$('#media-title-tv').click(function(){
        		if(active !='tv'){
        			$('#media-links-radio').hide('slide', {direction: 'left'}, 1000, function(){
        				$('#media-links-tv').show('slide', {direction: 'left'}, 1000);
        				$('#media-nav-bg').animate({
        					'width':'hide'
        				}, 'slow');
        				$('#media-seperator').animate({
        					'width':'show'
        				}, 'slow');
        			});
        			active = 'tv';
        			$('#media-title-tv').removeClass('media-title');
        			$('#media-title-tv').addClass('media-title-active');
        			$('#media-title-radio').addClass('media-title');      
					updatePlaylist($('ul#media-links-tv li:first a').attr('id').substring(10)); // added by fritz 08-09-2011 *** load the first video subcategory
        		}
        	});
        
        	$('#media-btn-add').click(function(){
        		if (!isAuthenticated) {
        			$('#media-btn-msg').jqmShow();
        		}
        		else{
        			if ($('#media-add-list').css('display') == "none") {
        				$('#media-btn-add').addClass('hover');
        				$('#media-add-list').css('display', 'block');
        			}
        			else {
        				$('#media-btn-add').removeClass('hover');
        				$('#media-add-list').css('display', 'none');
        			}
        		}
        	});
        	
        	$('#media-btn-watch').click(function(){
        		if (!isAuthenticated) {
        			$('#media-btn-msg').jqmShow();
        		}
        		else{
        			
        		}
        	});
        	
        	function redrawTitle() {
        		var bgWidth = ($("#content-wrapper").width() - 880) / 2;
        		$("#content-titlebg").remove();
        		$("#content-titlearea").append("<span id=\"content-titlebg\" style=\"width: " + bgWidth + "px !important\"></span>");
        	}
        	
        	$(window).resize(function() {
        		redrawTitle();
        	});
          // view more
          $('#videomore').click(function(){
        		 $('.btnshow').toggle();
        	  $('#video-moredetails').toggle('slow');
        	});        	
    }// media
    
});

// from http://www.nathancolgate.com/post/96953675/jquery-cycle-different-effects-for-previous-and-next (wawawaw)
$.fn.cycle.transitions.scrollBothWays = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push($.fn.cycle.commonReset);
	// custom transition fn (trying to get it to scroll forward and backward)
	opts.fxFn = function(curr, next, opts, cb, fwd) {
		
		var w = $cont.width();
		var h = $cont.height();
		opts.cssFirst = { top: 0 };
		opts.animIn	  = { top: 0 };
		
		if(fwd){
			opts.cssBefore= { top: h, left: 0 };
			opts.animOut  = { top: 0-h };
		}else{
			opts.cssBefore= { top: -h, left: 0 };
			opts.animOut  = { top: h };
		};
		
		var $l = $(curr), $n = $(next);
		var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animOut = opts.animOut, animIn = opts.animIn;
		$n.css(opts.cssBefore);
		var fn = function() {$n.show();$n.animate(animIn, speedIn, cb);};
		$l.animate(animOut, speedOut, function() {
			if (opts.cssAfter) $l.css(opts.cssAfter);
			if (!opts.sync) fn();
		});
		if (opts.sync) fn();
	};
};
