$(document).ready(function() {	

	// Image Slider
	if( $('#slider').length > 0 ){
		$('#slider ul').cycle({ 
			fx:      'fade',
			timeout:  6000,
			pause:    1
		});	
	}	
	
	// Case Studies Slider
	if( $('div.box_case_studies div.wrap ul').length > 0 ){
		$('div.box_case_studies div.wrap').cycle({ 
			fx:      'fade',
			timeout:  0,
			pause:    1,
			prev:    '.cs-prev',
			next:    '.cs-next'
		});	
	}
	
	// Plant Sales Slider
	if( $('.plant_item').length > 0 ){
		$('div.box_sales div.container').cycle({ 
			fx:      'fade',
			timeout:  0,
			pause:    1,
			prev:    '#plant-left',
			next:    '#plant-right'
		});	
	}
	
	// Clear Search Box
	$('input.search-box').focus(function(){
		if( $(this).val() === 'Search our site' ){
			$(this).val('');
		}
	});
	$('input.search-box').blur(function(){
		var title = 'Search our site';
		if($(this).val() === ''){
			$(this).val(title);
		}
	});
	
	// Search Validation
	$("#frmsearch").submit( function(){
		var term = $(this).find('.search-box').val();
		if(term == 'Search our site'){
			alert('Please enter a term to search for');
			$(this).find('.search-box').focus();
			return false;
		}
		return true;
	});


	// Clear/ Restore Text Boxes
	$('#quick_contact input.textbox').focus(function(){
		var title = $(this).attr('title');
		if($(this).val() === title){
			$(this).val('');
			$(this).css({ 'color':'#333' });
		}
	});
	$('#quick_contact input.textbox').blur(function(){
		var title = $(this).attr('title');
		if($(this).val() === ''){
			$(this).val(title);
			$(this).css({ 'color':'#b3b3b3' });
		}
	});
	
	// Services Select Box
	$('.box_services ul li').hover(function(){
		var title = $(this).children('a').attr('title');									
		$h4 = $(this).parent().prev('label');
		$h4.text(title).fadeIn();
	});
	
	// Client Logo Tooltip	
	$('#logos ul').each(function(index){
		$('li', this).each(function(indx){
			var id = $(this).children('a').attr('id');	
			var tt = '.' + id;
			if( $(tt).length ){				
				var content = $(tt).html();
				$(tt).remove();
				$(this).tinyTips(content);
			}
		});
	});
	
	
	// Quick Enquire default/ Focus
	if( $("input[name='status']").val() !== 'error' ){
		// Skip this if error has occured
		$("#quick .box_border").css('height', '182px').css('overflow', 'hidden');
		$("#captcha-quick").hide();
	}
	
	var timed = null;
	if( $("#quick_contact .textbox").length > 0 ){
		$("#quick_contact .textbox").each(function() {
			$(this).focus(function() {					
					
					$("#quick .box_border").animate({ 
						height: '275px'
					}, 500 );
					$("#captcha-quick").fadeIn();
					clearTimeout(timed);
					
			
			});
			$(this).blur(function() {
			
		
				timed = setTimeout(function(){
				
					$("#quick .box_border").animate({ 
						height: '182px'
					}, 500 );
					$("#captcha-quick").fadeOut();
					
				},2000);
				
			});
		});
	}
	
	// Quick Enquire Validation
	$("#quick_contact").submit(function(){
		var name = $(this).find("input[name='data[name]']").val();
		var email = $(this).find("input[name='data[email]']").val();
		var telephone = $(this).find("input[name='data[telephone]']").val();
		var enquiry = $(this).find("input[name='data[enquiry]']").val();
		var captcha = $(this).find("input[name='captcha']").val();
		
		var message = '';
		if(name == '' || name == 'Name'){ message += "- Enter your name\n" };
		if(email == '' || email == 'Email'){ message += "- Enter your email address\n" };
		if(telephone == '' || telephone == 'Telephone'){ message += "- Enter your telephone number\n" };
		if(enquiry == '' || enquiry == 'Enquiry'){ message += "- Enter your enquiry\n" };
		if(captcha.length < 5 || captcha == 'Security Code'){ message += "- Enter the correct security code\n" };
		
		if(message!==''){ 
			alert("Please fill out the required fields to enquire:\n\n"+message);
			return false;
		}
	});
	
	// Footer Contact
	$('#footer_contact').submit(function(){
		// Get data
		var postdata = $(this).serialize();
		
		// Submit data
		$.ajax({
			url: '/ajax.php',
			type: 'POST',
			data: postdata,
			success: function(data) {
				if(data == 'success'){
					window.location = '/contact/thank-you/';
				}else{
					$("div.message div").text(data);
					$("div.message").fadeIn('slow');
				}
			}
		});
		
		return false;
	});
	$("div.message").click(function(){
		$(this).fadeOut();
	});
	
	
	// Global Loader
	$('#loadingDiv')
    .ajaxStart(function() {
        $(this).fadeIn();
    })
    .ajaxStop(function() {
        $(this).fadeOut();
    });
	
	
	// Product Gallery
	$("#thumbnails a").click( function(){
		var name = $(this).attr('name');		
		$("#mainimage").attr('src', name);
	});
	
	
	// Translate Select
	if($.cookie('language')){
		$('body').translate($.cookie('language'));
	}
	$('.translateTrigger').change( function(){ 
		$.cookie('language', $(this).val(), { path: '/' }); 
		$('body').translate($(this).val()); 
	});	
	
});


$(window).load(function(){
						
	// Fade in images so there isn't a color "pop" document load and then on window load
	$('#clients_container ul').show();
	$("#logos ul li a img").fadeIn(500);

	// clone image
	$('#logos ul li a img').each(function(index){
		var el = $(this);
		el.css({"position":"absolute"}).wrap("<div class='img_wrapper'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
			var el = $(this);
			el.parent().css({"width":this.width,"height":this.height});
			el.dequeue();
		});
		
		if ($.browser.msie) { this.style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)"; }
      	else {  this.src = grayscale(this.src); }
				
	});

	// Fade image
	$('#logos ul li a img').mouseover(function(){
		$(this).parent().find('img:first').stop().animate({opacity:1}, 500);
	})
	$('.img_grayscale').mouseout(function(){
		$(this).stop().animate({opacity:0}, 500);
	});
	
	
	// Client Logo Slider
	if( $('#clients_container ul').length > 1){		
		$('#clients_container').cycle({
			fx:      'scrollHorz',
			timeout:  0,
			pause:    1,
			prev:    '.slider_left',
			next:    '.slider_right'
		});
	}
	
	// Product Categories
	$(".listrow h3 a").click(function(){
		$list = $(this).parent().parent().find('.listextend');
		var href = $(this).attr('href');
		if( $list.css('display') == 'none' ){
			$list.slideDown();
		}else{
			$list.slideUp();
		}
		if(href == '#'){ 
			return false;
		}
	});

	
});

// Text replacement
Cufon.replace('div.box_title span, h2, h3, .cufon', { hover: true });

// Grayscale w canvas method
function grayscale(src){
	var canvas = document.createElement('canvas');
	var ctx = canvas.getContext('2d');
	var imgObj = new Image();
	imgObj.src = src;
	canvas.width = imgObj.width;
	canvas.height = imgObj.height;
	ctx.drawImage(imgObj, 0, 0);
	var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
	for(var y = 0; y < imgPixels.height; y++){
		for(var x = 0; x < imgPixels.width; x++){
			var i = (y * 4) * imgPixels.width + x * 4;
			var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
			imgPixels.data[i] = avg;
			imgPixels.data[i + 1] = avg;
			imgPixels.data[i + 2] = avg;
		}
	}
	ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
	return canvas.toDataURL();
}

function show(element) {
	document.getElementById(element).style.display = 'block';		
}
function hide(element) {
	document.getElementById(element).style.display = 'none';	
}

function show_menu(element) {
	document.getElementById(element).style.display = 'block';		
}
function hide_menu(element) {
	document.getElementById(element).style.display = 'none';	
}

function loadMap() {
  if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		var point = new GLatLng(45.59536, -73.5763);
		
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(point, 15);
	
		function createMarker(point, html) {
			var marker = new GMarker(point);
			marker.openInfoWindowHtml(html);
			return marker;
		}
	
		map.addOverlay(createMarker(point, '<strong>EDS Decommissioning Canada inc</strong><br />6555, boul. Métropolitain Est<br />Bureau 505A, Montréal (Québec)<br />H1P 3H3, Canada<br />(514) 321-4343'));

  }
}
