/*
================================================================================================================================================
Title:        CSS - Index	Page
File:         general.js
Version:			1.0
Author:       Roman Leinwather
E-mail:       roman@thrudigital.com

================================================================================================================================================

TABLE OF CONTENT


1.  Twitter author	
2.  Customer's logos
3.  Home page - Recent Post/Most Popural Post Section
4.  Main Navigation
5.  Portfolio - hiden description
6.  Form textarea height auto adjustments	
7.  Blog - categories list
8.  Blog - Form
9.  Archive list
10. Footer Form Ajax
11. Ask a Question button
	
================================================================================================================================================
*/


// 1. Twitter author
// Function puts spans around charles name so it could be styled
// Note: If there are more authors this will need to be adjusted, using reg exp.
/*
$(function (){
  
  $('#twitter_column li a').each(
    
    function (){
      $linkElement = $(this);

      // Define the team member's twitter accounts
      team = new Array();
      team[0] = 'cdaltonmoore';
      team[1] = '36degrees';
      team[2] = 'andjdavies';
      team[3] = 'lewro';
      team[4] = 'pierslowe';
  
      // Loop through all team members / links and replace the user names with spans, get rid of the Tweet by message...
      $.each(team,
      function(intIndex, objValue){
        
        // Add span tags around names
        $($linkElement).html($($linkElement).html().replace(objValue,'<span class="' + objValue + '">' + objValue + '</span>'));
        
        // remove the "Tweet by" message
        $($linkElement).html($($linkElement).html().replace('- Tweet By:@',''));
      
      
        $('.' + objValue + '').each(
          function(){
           // take the names and insert them at the begining of the link
           ($(this).parents('li').find('a')).prepend($(this));
        }); 
      });
    });
});
*/

// 2. Customer's logos
// Function calculates the top margin for each image and sets the css
// LOG: 27/10/2009 by Roman - I put the timeout in there because if the page has loaded slowely the margin was applied equaly to all images which broke the layout. 
$(function(){
	setTimeout("customersImages()",1500);
});



function customersImages(){
  $('#our_customers li').each(
    function (){

    // Find the list element height
    $listHeight = $(this).height();    
      
    // Find the image height
    $image = $(this).children()[0];
    $imageHeight = $($image).height();
    
    // Calculate the top margin
    $topMargin = ($listHeight - $imageHeight) / 2; 
    $marginInPixels = $topMargin + 'px';
    
    // set the margin-top for the image
    $($image).css({"margin-top" : $topMargin});
    
  });
}


// Hover effects for dinamicly uploaded cutomer's logos
$(function(){
	$('#our_customers li img').hover(
	 
    function (){
      $src = $(this).attr("src").replace('supporters','supporters_colour');
      $(this).attr("src", $src);
	 },
	   function (){
      $src = $(this).attr("src").replace('supporters_colour','supporters');
      $(this).attr("src", $src);
	 });
});


// 3. Home page - Recent Post/Most Popural Post Section
// Function inserts the navigation and handles the switchin between sections

// Generate navigation 
// Assign switch for sections (animation?)
$(function (){

  // Generate the navigation
  $('<ul id="nav_blog"><li id="nav_recent_posts" class="active">Recent Posts</li><li id="nav_mostpopular_posts">Most popular posts</li></ul>').insertBefore('#latest_blog_posts');

  // Hide the most popular section
  $('#most_popular').hide();

  // Define the anmiation speed
  $delay = 700;

  // Switch the section
  $('#nav_recent_posts').click(
   function(){ 
    
    // Tabs
    $('#nav_blog li').removeClass('active');
    $(this).addClass('active');
    
    
    $('#latest_blog_posts').show().css({"opacity":0}).animate({"opacity":1},$delay);    
    $('#most_popular').hide();    
    
  });
  
  $('#nav_mostpopular_posts').click(
   function(){ 
   
    // Tabs
    $('#nav_blog li').removeClass('active');
    $(this).addClass('active');

    $('#latest_blog_posts').hide();
    $('#most_popular').show().css({"opacity":0}).animate({"opacity":1},$delay);
  });
  
});

// 4. Main Navigation
$(function (){

  // Make sure you are targeting only the top level links
  $('#nav1 li a:first-child').addClass("activeNav");
  $('#nav1 li ul li a').removeClass("activeNav");
  
  // Add class to subnavigatioin for easier targeting
  $('#nav1 li ul').addClass("aciveSubNav");
  
  // Add class to last link in the subnavigation so the bottom bg image can be styled
  $('.aciveSubNav :last-child').addClass("lastNav");

  $('.activeNav').hover(
    function(){

        $subNav = $(this).next($('.aciveSubNav'));
        $height = $($subNav).height();
        $speed = 150;
        
        // TODO: Add condition so it does not open when it is already opened...
        // Add Class to slideDown list and remove it on hover out after 0,5 sec.
        $(this).addClass("active");
        $subNav.stop(true, true).slideDown($speed);
    },
  
    // on hover out
    function (){
      $(this).removeClass("active");
      $subNav.stop(true, true).hide(); 
      $('#nav1 li ul').stop(true, true).hide(); 
    });
    
    // When the mouse is over subnav keep it displayed
    $('.aciveSubNav').hover(
    function(){
      $(this).show();
            
      // Add class to subnavigation header so it can be highlighted
      $headerLink = $(this).prev($('.activeNav'));
      $headerLink.addClass("active");
    },
  
    // on hover out
    function (){
      $(this).hide();
      $headerLink = $(this).prev($('.activeNav'));
      $headerLink.removeClass("active");
    });
});

// 5. Portfolio - hiden description
$(function(){
  $('<a class="read_more" href="#" title="read more">read more</a>').insertBefore(".hiden_description");
    
  $(".read_more").toggle(
        function() {
            $(this).next().slideDown();
            $(this).text("hide").attr({
              "class":"hide_description", 
              "title":"hide description"
            });
        },
        function() {
            $(this).next().slideUp();;
            $(this).text("read more").attr({
              "class":"read_more", 
              "title":"read more"
            });
        }
    );
});


// 6. Form textarea height auto adjustments
// Adjust the height of the box
// This can be reused - the cover section will not be neccessary in other cases....
$(function(){
  $textarea = $('#contact_us_wrapper form textarea');             // Set the textarea 
  $characterLimit = 105;                                          // Maximum number of characters in single line
  
  $originalHeight = $($textarea).css("height").replace("px","");  // Height of signle line (without 'px')
  
  $textarea.keyup(function(){
    $currentCharacters = $($textarea).val().length;               // Actual amount of characters
    $heightRatio = $currentCharacters / $characterLimit;          // Get the ratio of characters and round the number
    $roundRatio = Math.round($heightRatio);                       // Round the ration so it can be used for new height calculation

    if($currentCharacters > $characterLimit){
      // Calculate new height for textarea     
      $newHeight = (parseInt($originalHeight)) * $roundRatio + "px";
      // Set the new heights
      $($textarea).stop().animate({height: $newHeight},500); 
    }else{
      $($textarea).stop().css({height: $originalHeight}); 
    }
  });
});

// 7. Blog - categories list
$(function(){

  $catList = $('#categories ul');
	$('#categories h3').addClass("clicked");
	
	$('#categories h3').click(function(){
  
    if ($(this).hasClass("clicked")){
  	   $(this).removeClass("clicked");
  	   $($catList).slideUp(500);
  	 }else{
  		$(this).addClass("clicked");
  		$($catList).slideDown(500);	
    }		
	});
});


// 8. Blog - Form
$(function(){
  if($('#commentform').length == 0){
    // no comment form...  
  }else{    
    // Remove values on click  
    $('#commentform input').focus(function(){
    
      // Get the ID of the element and covert it to our label
      $id = $(this).attr("id") + ": ";  
      
    	
    	// If there is default value
    	if($(this).val() == $id){
    	 // Remove the value
    	 $(this).val("");
    	
    	}
    });
  
  
    // On blur check if the element is empty 
    // if so use the default value... 
    $('#commentform input').blur(function(){
      $id = $(this).attr("id") + ": ";  	
  
    	if($(this).val() == ""){
    	  $(this).val($id);
    	}
    });
    
    
    // On submit - Check if any of fields has got default values 
    // if so remove them
    $('#commentform').submit(
      function(){
         $('#commentform input').each(
          function(){
            if($(this).val() == ($(this).attr("id") + ": ")){
              // remove the default value
              $(this).val("");
            }
          });
    });
      
  
    // Adjsut the height of the textarea if needed
    // TODO: The same functionality used in the footer form - rework so only one code is used...
    
    $textarea = $('#commentform textarea');             
    $characterLimit = 205;                                           
    
    $originalHeight = $($textarea).css("height").replace("px","");  
    
    $textarea.keyup(function(){
      $currentCharacters = $($textarea).val().length;               
      $heightRatio = $currentCharacters / $characterLimit;          
      $roundRatio = Math.round($heightRatio);                       
  
      if($currentCharacters > $characterLimit){
        // Calculate new height for textarea     
        $newHeight = (parseInt($originalHeight)) * $roundRatio + "px";
        // Set the new heights
        $($textarea).stop().animate({height: $newHeight},500); 
      }else{
        $($textarea).stop().css({height: $originalHeight}); 
      }
    });
  }
});

// 9.  Archive List
$(function(){
	$('#blog_archive_by_month ul').hide();
	$('#blog_archive_by_month h4').click(function(){
		if($(this).attr("class") == 'active'){
			$(this).next().fadeOut();
			$(this).removeClass('active');			 
   		return false;
		}else{
			$(this).next().fadeIn();
			$(this).addClass('active');
			return false;	
		}
	});
});

//  10. Footer Form AJAX
function validate_footer_form($url){
	$('#footer_contact_form').submit(function(){
  // Remove success and error messages
  $('.error_message').remove();
  $('#success_message').remove();

	 var error = new Array();
   var empty_input = 0;    
   
    // Validation 	
	  // 1.Check if the fields are not empty
    $("#footer_contact_form input").each(function(){
		  if($(this).val() == ""){
        empty_input ++;
		  }
		});
		
		if($("#footer_contact_form textarea").val() == ""){
        empty_input ++;		
		}
		
		if(empty_input >0){
		  error.push("Please fill all data");
		}
		
    var email =  ($('#email').val());			
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    
    // 2. Check the email address
    if(!filter.test(email)){	
       error.push("Please provide correct email address");
    }
    
    /* 3.
    No Captcha fo now...
    Check if the calculation is correct
    
    if($('#simple_captcha').val() !=="2"){
      error.push("Please provide the right calculation");
    }    
    */
    
    if($(error).size() > 0){
      $(error).each(function() {
        $('<p class="error_message">'+ this +'</p>').insertBefore('#submit_cover');
          $('.error_message').hide();
          $('.error_message').fadeIn(1000);
      });
    }else{
      
      // All good - fire the ajax
      dataString = $("#footer_contact_form").serialize();       
            
      $.ajax({  
        type: "POST",  
        global: false,
				url: $url,         
        data: dataString,
        //dataType: "json",
       
        success: function() {
          if($('.success_message').length == 0){ 
            $('<p class="success_message">Thank you for your message!</p>').insertBefore('#submit_cover');
            $('.success_message').hide();
						
						// Clear the form
						$('#footer_contact_form input').val("");
						$('#footer_contact_form textarea').val("");
            
						$('.success_message').fadeIn(1000);
            fade_sucess_message();
          }else{
            $('.success_message').show();
          }
        }
      });
    }

    $('.error_message').click(function(){
  		$(this).fadeOut(1000);
  	});

    function fade_sucess_message (){       
      $('.success_message').click(function(){
    		$(this).fadeOut(1000);
    	});
    }
  return false;  
  });
}

// 11.  Ask a Question Button
$(function(){

  $time = 1000;

	if($('#read_more').lenght == 0){
	}else{
	 $('#read_more').click(function(){
	    // set view position
      var w_height = $(document).height();
      var w_position = (w_height - 20);
      $('html, body').animate({
        scrollTop: w_position
      },'slow'); 
      
      //Animate the width of all form elements
      $('#footer_contact_form #form_1 input, #footer_contact_form #form_2 textarea').css({
        "background" : "#d9f1f3",
        "width" : "20px"
        }).animate({
        width: "240px"
      },$time);
      
      // chnage the bg colour back to white
      setTimeout(
        function(){
          $('#footer_contact_form #form_1 input, #footer_contact_form #form_2 textarea').css("background", "white");
          $('#footer_contact_form #form_1 input:first').val("First things first");
          setTimeout(
            function(){
              $('#footer_contact_form #form_1 input:first').focus().val("")
            }
          ,$time/1.5);
        }
        ,$time);
      return false;
	 });
  }
  
});