/* 
	Title: T Clarke - Global JavaScript document
	Description: Contains any custom JavaScript functions
	Version: 0.1
	Author: Ben Ellis
	Author URI: http://www.hungrybrowser.co.uk
	Created: 20/10/2011
	Updated: 08/11/2011
*/

/* ------------------------------------------------------------
	Declare the global functions
---------------------------------------------------------------- */

/*
	Function to add custom event tracking to an object using Google Analytics
	@param: id = id of the object to target
	@param: category for the event
	@param: action for the event
	@param: title of the event
*/
function trackEvent(id,category, action, title){
	$(document).ready(function(){
		// Attach the event
		$(id).click(function(){
			_gaq.push(['_trackEvent', category, action, title]);
		});
	});
}

/* 
	Function to scroll the page
	@param: nav_id = id of the link to attach the event to
	@param: target_id = id of the object to scroll to
	@param: nav_id = id of the nav container
	@param: nav_id = id of the active nav item
*/
function backToTop(triggerId,targetId){
	$(document).ready(function(){
		// Attach the onclick event
		$(triggerId).click(function(){
			// Scroll the page
			$('html, body').animate({
				scrollTop: $(targetId).offset().top
			}, 500);	
			// Ensure that the anchors don't make the page jump 
			return false;
		 });
	})
}

/* Funciton to create homepage slider */

function slider(id){
	// Only show for non-mobile devices
	if ($(window).width() > 480){
		// Run the slider function
		$(document).ready(function() {
			// Find the slide wrapper
			$(id)
				// Run the carousel
				.carousel({
					slider: 'ul',
					slide: 'li',
					addNav: true,
					addPagination: true,
					speed: 300 // ms.			
			});
		});
	}
}

/*
	Function to launch a lightbox contact form (size chart etc.)
	@param: triggerId = the id/class of the link
*/
//function contactForm(id,type){
//    
//    $.ajax({
//    type: "GET",
//    url: "/index.php/contact/index?id="+id+"&type="+type,
//    success: function(html){
//       $.fancybox(html);
//        },
//    error: function(){
//        return false;
//    }
//    });
//    
//    
//    
//}
function contactForm(id){
  
	$(document).ready(function(){
		// Not for internet explorer (fancybox bug)
		if ($.browser.msie) {
			$(id).attr('target', '_blank');
		}
		// For any screen size bigger than an iPhone
		else if($(window).width() > 768){
		
			// Attach the onclick event
			$(id).fancybox({
				'width':  640,
				'height':  650,
                                'border-width': 15,
				'scrolling' : 'no',
				'autoDimensions': false,
				'autoScale'     	: false,
				'titleShow'		: false,
				'type'			: 'iframe'
			});
		}
		// Else launch the item in a new window
		else $(id).attr('target', '_blank');
                
             
                        

	});
          $('#fancybox-content').css('border-width','15px !important');
}

/*
	Function to launch a new window
	@param: triggerId = the id/class of the link
*/
function newWindow(id){
	$(document).ready(function(){
		$(id).attr('target', '_blank');
	});
}


/*
	Function to toggle the visibility of an element
	@param: triggerId = id/class for the items to slide
*/

function toggleElement(id){
	$(document).ready(function(){
		// Attach onclick events to the nav item
		$(id).click(function(e){
			// Prevent the default
			e.preventDefault();
			// Get the id for the current div from the nav #href
			var activeDiv = $(this).attr('href');
			// Toggle the opacity of the form
			$(activeDiv).slideToggle(200);
			// Set the current class for the active nav item
			$(this).toggleClass('selected');
		});
	});
}

/*
	Function to show/hide the different page elements
	@param: triggerId = the id/class of the navigation items
	@param: targetId = the id/class of the div items
*/
function toggleSection(triggerId,targetId){
	$(document).ready(function(){
		// Go through all the nav and attach onclick events
		$(triggerId).click(function(){
			// Remove all the active classes from the nav
			$(triggerId).removeClass('selected');
			// Set the current class for the active nav
			$(this).addClass('selected');
			// Remove all the active classes for the divs
			$(targetId).removeClass('selected');
			// Get the id for the current div from the nav #href
			var activeDiv = $(this).attr('href');
			// Set the current class for the active div
			$(activeDiv).addClass('selected');
			// Ensure that the anchors don't make the page jump 
			return false;
		});
	});
}

/*
	Function to apply an style to a specific element
	@param: triggerId = the id/class of the navigation items
	@param: targetId = the id/class of the div items
*/
function toggleClass(triggerId,targetId){
	$(document).ready(function(){
		// Go through all the nav and attach onclick events
		$(triggerId).click(function(){
			// Remove all the active classes from the nav
			$(triggerId).removeClass('selected');
			// Set the current class for the active nav
			$(this).addClass('selected');
			// Remove all the active classes for the divs
			$(targetId).removeClass();
			// Get the class from the link href
			var activeClass = $(this).attr('href');
			// Replace the hash sign with a dot
			activeClass = activeClass.replace('#',''); 
			// Set the current class for the active div
			$(targetId).addClass(activeClass);
			// Ensure that the anchors don't make the page jump 
			return false;
		});
	});
}

function toggleLinks(triggerId,targetId){
	$(document).ready(function(){
		// Go through all the nav and attach onclick events
		$(triggerId).click(function(){
			// Remove all the active classes from the nav
			$(triggerId).removeClass('selected');
			// Set the current class for the active nav
			$(this).addClass('selected');
			// Get the id from the link href
			var activeDiv = $(this).attr('href');
			// Remove all the active classes for the divs
			$(targetId).removeClass();
			// Get the id from the link href
			var activeDiv = $(this).attr('href');
			// Set the current class for the active div
			$(activeDiv).addClass('selected');
		});
	});
}

/*
	Function to launch an inline lightbox (size chart etc.)
	@param: id = the id/class of the link
*/
function flickr(id){
	$(document).ready(function(){
		// Not for internet explorer (fancybox bug)
		if (0==1) {
			$(id).attr('target', '_blank');
			alert($.browser.msie+' '+$.browser.version);
		}
		// For any screen size bigger than an iPhone
		else if($(window).width() > 640){
		
			// Go through each photo and rewrite the img URL
			$(id +' li a').each(function() {
				var imgSrc = $(this).children().attr('src');
				$(this).attr('href',imgSrc.replace('_m.jpg','.jpg'));
			});
		
			// Attach the fancy box overlay
			$(id +' li a').fancybox({
				'transitionIn'		: 'fade',
				'transitionOut'		: 'fade',
				'titlePosition' 	: 'over',
				'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
				    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
				}
			});
		}
		// Else launch the item in a new window
		else $(id +' li a').attr('target', '_blank');
	});
}
function youTubeLightbox(id){
	$(document).ready(function(){
		// Not for internet explorer (fancybox bug)
		if ($.browser.msie) {
			$(id).attr('target', '_blank');
		}
		// For bigger screen sizes
		else if($(window).width() > 640){
		
			// Attach the onclick event
			$(id).fancybox({
				'autoDimensions': true,
				'autoScale'     	: true,
				'titleShow'		: false,
				'type'			: 'iframe'
			});
		}
		// Else launch the item in a new window
		else $(id).attr('target', '_blank');
	});
}
/* Function to ensure YouTube vids go underneath the lightbox 
	@param: id = the id/class of the link
*/

function youTube(id){
	$(document).ready(function(){
		$(id).each(function(){
		    var url = $(this).attr("src");
		    $(this).attr("src",url+"?wmode=transparent&rel=0");
		});
	});
}


/*
	Function to toggle the visibility of a video
	@param: triggerId = id of the video container div
*/
function toggleVideo(id){
	$(document).ready(function(){	
		// Open video button
		$(id+' a.open').click(function(){
			// Get the video id
			var videoId = $(this).attr('href');
			// Hide the image
			$(videoId+' img').toggleClass('hidden');
			// Show the video
			$(videoId+' div').toggleClass('selected');
			// Show the close button
			$(videoId+' p').toggleClass('selected');
			// Ensure that the anchors don't make the page jump 
			return false;
		});
		// Close video button
		$(id+' p a').click(function(){
			// Get the video id
			var videoId = $(this).attr('href');
			// Get the video url 
			var videoURL = $(videoId +' iframe').attr('src');
			// Stop the video (reset the src)
			$(videoId+' iframe').attr("src",videoURL);
			// Hide the video
			$(videoId+' div').toggleClass('selected');
			// Hide the close button
			$(videoId+' p').toggleClass('selected');
			// Show the image
			$(videoId+' img').toggleClass('hidden');
			// Ensure that the anchors don't make the page jump 
			return false;
		});
	});
}

/*
	Function to create the locations map (Google Maps API V 3)
	@param: map_id = the id of the map canvas
	@param: map_lat = the map latitude to centre the canvas on
	@param: map_long = the map longitude to centre the canvas on
	@param: map_zoom = the zoom level for the map
	@param: map_data = the path to the xml file for the map data
	
	mapId,mapLat,mapLong,mapZoom,mapData
*/
function locationsMap(map_id,map_lat,map_long,map_zoom,map_data){
	$(document).ready(function(){
		// Coordinates for map centre
		var map_centre = new google.maps.LatLng(map_lat, map_long);
		// Map interface options
		var myOptions = {
				zoom: map_zoom,
		  		center: map_centre,
		  		mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		// Add the map canvas
		var map = new google.maps.Map(document.getElementById(map_id),myOptions);
		// Use jQuery to get the XML data
		$.get('/location/getLocations', {}, function(data){
			// Loop through the markers
                         var obj = jQuery.parseJSON(data);
                  //     console.dir(obj);
			$.each(obj,function(index,val){
                          
				var marker = $(this);
				// Lat
				var lat = parseFloat(val.lat);
				// Long
				var lng = parseFloat(val.lng);
				// Marker point
				var latlng = new google.maps.LatLng(lat,lng);
				// City
				var city = val.city;
				// Business
				var business = '';// marker.attr("business");
				// Address
				var address = val.address;
				// Tel
				var tel = val.tel;
				// Fax
				var fax = val.fax;
				// HTML 
				var html = "<div class=\"info_window\"><h2><a href=\"#\" title=\""+city+"\">"+city+"</a></h2><address><strong>"+business+"</strong>"+address+"</address><strong>T:</strong>"+tel+"<br /><strong>F:</strong>"+fax+"</div>";
				// Add the markers
				var marker = new google.maps.Marker({position: latlng, map: map});
				// Map info
				var map_info_window = new google.maps.InfoWindow({content: html});
			    // Add the info window
				google.maps.event.addListener(marker, 'click', function(){
					map_info_window.open(map,marker);
				});  
			});
		});	
	});
}

/* ------------------------------------------------------------
	Execute the global functions
---------------------------------------------------------------- */

$(document).ready(function(){
	// Responsive videos
	$("#page").fitVids();
	
	// Footer sitemap
	toggleElement('#footer_sitemap .wrapper h2 a');
	
	// Flickr photos
	flickr('#flickr');
	
	// YouTube
	youTube('iframe');
	
	// Back to top link 
	backToTop('#back_to_top p a','#page');
	
	// Firefox 3.0 hack to add n-th child support
	$("#twitter ul li:nth-child(even)").addClass('dark');
	$("#v1 .showcase ul li:nth-child(4n+1)").addClass('no_margin');
	$("#businesses.showcase ul li:nth-child(2n+1)").addClass('no_margin');
	$("#case_studies .showcase ul li:nth-child(3n+1)").addClass('no_margin');
	$("ul#locations li:nth-child(3n+1)").addClass('no_margin');
	$("#error_404 li:nth-child(odd)").addClass('no_margin');
	$("#investors li:nth-child(odd)").addClass('no_margin');
	$(".full_width ul#locations li:nth-child(3n+1)").removeClass('no_margin');
	$(".full_width ul#locations li:nth-child(4n+1)").addClass('no_margin');

});



function getFile(file){
   
    window.open('/uploads/media/'+file,"tclarke file", " resizable, scrollbars"); 

}

function newsAddPoint(id, url){
    
  $.ajax({
    url: "/index.php/news/addPoint?news_id="+id,
    cache: false,
    async: false,
    success: function(){
        
        location.href('/news/'+url+'.html');
        },
    error: function(){
        return false;
    }
    });
}
function noticeboardAddPoint(id, url){
    
  $.ajax({
    url: "/index.php/noticeboard/addPoint?notice_id="+id,
    cache: false,
    async: false,
    success: function(){
        
        location.href('/noticeboard/'+url+'.html');
        },
    error: function(){
        return false;
    }
    });
}

function casestudyAddPoint(id){
    
  $.ajax({
    type: "GET",
    url: "/index.php/showcase/addPoint?showcase_id="+id,
    cache: false,
    async: false,
    success: function(){
        return true;
        },
    error: function(){
        return false;
    }
   
    });
}

function newsByMonth(month){
    month = month.split(","); 

    window.location='/news/index?month='+month[0]+'&year='+month[1];

}
function noticeboardByMonth(month){
    month = month.split(","); 

    window.location='/noticeboard/index?month='+month[0]+'&year='+month[1];

}

function rememberView(view){
    
     $.ajax({
    type: "GET",
    url: "/index.php/main/rememberView?view="+view,
    cache: false,
    async: false,
    success: function(){
        return true;
        },
    error: function(){
        return false;
    }
   
    });
}

function getProfileById(id){

    $('.loading').css('display', 'block');
    $.ajax({
    type: "GET",
    url: "/index.php/contact/getProfileById?id="+id,
    cache: false,
    //async: false,
    success: function(data){
       $('#people_profile .experience').empty();
       var obj = jQuery.parseJSON(data);
     $('.loading').css('display', 'none');
     $('#people_profile .profile .office').empty();
     if(obj.photo !== ""){
          $('#people_profile .profile .img').empty().html('<img src="/uploads/media/'+obj.photo+'" alt="" width="190" height="150" />');
     }
    
     $('#people_profile .profile h4').empty().html(obj.name);
     $('#people_profile .profile p em').html(obj.job_position);
     if(typeof obj.experience !== 'undefined'){
          
          $('#people_profile .profile h5').empty();
          $('#people_profile .experience').css('height', '130px');
          $('#people_profile .profile .experience').html('<h5>Experience</h5><ul>');
          $.each(obj.experience, function(key, value) { 
             $('#people_profile .profile .experience').append('<li><a href="/our-locations/'+value.location_slug+'/'+value.url+'.html">'+value.name+'</a></li>');
        });
          
         
          $('#people_profile .profile .experience').append('</ul>');
     }else{
         $('#people_profile .experience').css('height', '20px');
     }
     
     $('#people_profile .profile p em').html(obj.job_position);
     $('#people_profile .profile p#fancy_button').html('<a href="/person/contact.'+obj.id+'.html?show=lightbox" class="button">Get in touch</a>');
     generate_fancybox();
        },
    error: function(){
       console.log('error');
    }
   
    });
}

function getProfileByName(type){
 $('#people_profile .profile h5').empty();
 $('#people_profile .profile h4').empty();
 $('#people_profile .profile .img').empty();
 $('#people_profile .profile .experience').empty();
 $('#people_profile .profile p em').empty();
 $('#people_profile .profile .office').empty();
 $('#people_profile .profile #fancy_button').empty();
 
 $('.loading').css('display', 'block');
    var worker_name ='';
    var params= '';
   /// var office = $('#people_office_search option:selected').val();
    if(type == 'name'){
          worker_name = $('#people_search_field').val();
          params = 'name='+worker_name;
    }else if(type == 'office'){
       
         var office = $('#people_office_search option:selected').val();
         if(office == '0'){
             params='';
         }else{
              params = 'office='+office 
         }
        
    }
    var dclass = "profile_row white";
    var i=0;
    $.ajax({
    type: "GET",
    url: "/index.php/contact/getProfileByName?"+params,
    cache: false,
    async: false,
    success: function(data){
      
     var l;
     var letters = [];
     var found =0;
       $('.loading').css('display', 'none');
       var obj = jQuery.parseJSON(data);
     
       if(obj == null){
             $('#people_results ul').empty();
             $('#people_results ul').html('<div class="not_found_notice"><p>There were no contacts matching your search criteria. You may wish to contact our head office instead.<p></div>');
             $('.message').html('0 contacts found');
             $('#people_profile .profile h4').empty().html('London (Head office)');
             $('#people_profile .experience').css('height', '20px');
             $('#people_profile .profile .office').empty().html('<br>T Clarke<br>45 Moorfields<br>London, EC2Y 9AE <br><br> T: +44 (0)20 7358 5000<br>F: +44 (0)20 7701 6265<br>\n\
                <a class="map" target="_blank" title="View on Google Maps" href="http://maps.google.co.uk/maps?q=Stanhope House 116-118 Walworth Road London SE17 1JY &hl=en&ll=51,491872,-0,098241&spn=0.009072,0.022724&sll=51,491872,-0,098241&sspn=0.009072,0.030899&vpsrc=0&gl=uk&hnear=Stanhope House 116-118 Walworth Road London SE17 1JY &t=m&z=160">View on Google Maps</a><br>\n\
                <br><a href="/our-locations/london.vcf" title="Download vCard">Download vCard</a>');
             $('#people_profile .profile p#fancy_button').html('<a class="button" title="Contact" href="/our-locations/contact.1.html?show=lightbox">Contact</a>');
                     
            generate_fancybox();
            
        }else{
         $('#people_results ul').empty();
         $.each(obj, function(key, val){
              l = val.lastname.slice(0,1);
              letters.push(l);
              
         })
         letters.sort();
         $.unique(letters);
         letters.sort();
       
         $.each(letters, function(key, val){
         $('#people_results ul').append('<li id="people_'+val.toLowerCase()+'"><h2>'+val+'</h2>');
         $.each(obj, function(k,name){
                   
                    if(name.lastname.slice(0,1) == val){
                        i++;
                       if(i/2==1){
                           dclass= "profile_row gray"
                       }else{
                           dclass= "profile_row white"
                       }
                        $('#people_results ul').append('<li class="'+dclass+'"><h3><a onclick="getProfileById('+name.id+')">'+name.name+'</a></h3><p><em>'+name.job_position+'</em></p></li>'); 
                         var o ={words:worker_name};
                         
                     highlight("people_results h3",  o);
                     found++;
                }
                         
                })
                i=0;
         $('#people_results ul').append('</li></ul>');
         })
         $('.message').html(''+found+' contacts found');
       }
       return false;
    },
    error: function(){
       $('#people_results ul').html('<div class="not_found_notice"><p>There were no contacts matching your search criteria.\n\
            You may wish to contact our head office instead.<p></div>');
    }
   
    });
}

function getProfileByOffice(){
    var office = $('#people_office_search option:selected').val();
    
    if(office!== '-1'){
     $(window.location).attr('href', '/contact/our-people.html?office='+office);
    }else
    {
        $(window.location).attr('href', '/contact/our-people.html');
    }


}



function highlight(id, options) {
    //console.log(id);
   // console.dir(options);
  var o = {
    words: '',
    caseSensitive: false,
    wordsOnly: true,
    template: '$1<span class="highlight">$2</span>$3'
  }, pattern;
  $.extend(true, o, options || {});
 
  if (o.words.length == 0) { return; }
  pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', o.caseSensitive ? "" : "ig");
 
  $('#'+id).each(function() {
    var content = $(this).html();
    if (!content) return;
    
    $(this).html(content.replace(pattern, o.template));
    });
  }
  
  function scroll_to(div){
    
 
    value='li'+div;
    $('#people_results').scrollTo( value, 800 );
    
 
  }
  function handleEnter(inField, e) {
    var charCode;
    
    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        alert("Enter was pressed on " + inField.id);
    }
} 
