/**
* copyright @ GBF media OÜ
* author: Kristo Kiis
*/
var debug = false;
var Form = {
	init: function() {
		if ($('.formSubmit') && $('.formSubmit').length > 0) {
			$('.formSubmit').click(function(e) {
				id = $(this).attr('id').replace('formSubmit_', '');
				if ($(this).hasClass('justSubmit')) {
					$('#form_' + id).submit();
				} else {
					Form.validate('form_' + id, $('#form_' + id).attr('action'));
				}
				e.preventDefault();
			});
		}
		if ($('.autovalue') && $('.autovalue').length > 0) {
			$('.autovalue').each(function(item) {
				Form.autovalue($(this));
			});
		}
		$('.select').click(function(e){
			$('.drop-down').slideDown('fast', function(){
				$(window).click(function(){
					$('.drop-down').hide();
					$(window).unbind('click');
				});
			});
			e.preventDefault();
		});
		$('.drop-down').find('a').click(function(){
			$('.select-area').find('a:first').html($(this).html());
			$('#contact_subject').val($(this).html());
			$('.drop-down').hide();
		});
		$(".slide-bar").slider({
			min: 100,
			max: 10000,
			step: 50,
			value: 100,
			slide: function( event, ui ) {
				$("#price").html( ui.value );
				$("#price_val").val(ui.value);
			}
		});
	},
	validate: function(id, url) {
		var formData = {};
		error = false;
		$("#" + id).find("input[type='text'], input[type='checkbox']:checked, input[type='email'], input[type='url'], input[type='number'], input[type='radio']:checked, input:hidden, input[type='password'], textarea, select").each(function() {
			if (typeof values != "undefined" && this.value == values[this.name] && $(this).hasClass('required')) {
				$(this).addClass("error");
				error = true;
			} else {
				$(this).removeClass("error");
			}
			$('.error:first').focus();
			if ($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio') {
				if ($(this).is(':checked')) formData[this.name] = this.value; else formData[this.name] = 0;
			} else {
				if ($(this).find(':selected').length > 1) {
					name = this.name;
					formData[name] = [];
					$(this).find(':selected').each(function(i) {
						formData[name][i] = this.value;
					});
				} else {
					formData[this.name] = this.value;
				}
			}
		});
		if (error == false) {
			$.ajax({
			   	type: "POST",
			   	url: url,
			   	data: formData,
				dataType: "JSON",
			   	success: function(result){
					success = true;
					if (typeof(result)=="object"){
						if (id == 'pollForm') {
							Form.parsePoll(id, result);
						} else {
							$.each(result.status, function(field, status){
								current_field = $("#" + id).find("input[name='" + field + "']");
								if (status!="ok"){
									success = false;
									if (current_field.attr('type') == 'checkbox') {
										current_field.parent().first().prev().css('color', '#CC6A6C');
									} else {
										current_field.addClass("error");
									}
								} else {
									if (current_field.attr('type') == 'checkbox') {
										current_field.parent().first().prev().css('color', '');
									} else {
										current_field.removeClass("error");
									}
								}
							});
							if (success || result.status == 'ok'){
								$("#" + id).parent().find(".contentError").hide();
								$("#" + id).parent().find(".contentSuccess").show();
								$("#" + id).hide();
								if (result.redirect) {
									$.get(result.redirect, function(html) {
										$('#cms-content').html(html);
										$('body').animate({ scrollTop: 0 }, "slow");
										CMS.initPage();
									});
								} else if (result.http_redirect) {
									window.location = result.http_redirect;
								}
							} else {
								$("#" + id).parent().find(".contentError").show();
							}
						}
					}
			  	}
			});
		} else {
			$("#" + id).parent().find(".contentError").show();
		}
	},
	parseFormValues: function(scope, url) {
		$.ajax({
			type: "GET",
			url: url,
			dataType: "JSON",
			success: function(result){
				$("#" + scope).find('form').find("input[type='text'], input[type='checkbox'], input[type='radio'], input:hidden, textarea, select").each(function() {
					if (result[this.name] && result[this.name] != 0) {
						if ($(this).attr('type') == 'checkbox') $(this).attr('checked', 'checked'); else $(this).val(result[this.name]);
					} else {
						if ($(this).attr('type') == 'checkbox') $(this).removeAttr('checked'); else $(this).val('');
						if (debug) console.warn('input not found from an array:' + this.name);
					}
				});
			}
		});	
	},
	autovalue: function(item) {
		values = {};
		item.find("input[type='text'], input[type='password'], textarea").each(function() {
			values[this.name] = this.value;
			$(this).bind('blur', function() {
				if (this.value=='')
					this.value=values[this.name];
			});
			$(this).bind('focus', function(){
				if (this.value==values[this.name])
					this.value='';
			});
		});
	}
}
var Slider = {
	init: function() {
		Slider.timer1 = false;
		Slider.total_elements = $('.slide-content').length;
		Slider.element_width = $('.slide-content:first').width();
		Slider.visible_area = $('.slide-area').width();
		$('.slide-inner').width(Slider.total_elements*Slider.element_width);
		buttons = Math.ceil((Slider.total_elements * Slider.element_width) / Slider.visible_area);
		for (i=0;i<buttons;i++) {
			$('.slide-buttons').append('<li><a' + (i == 0 ? ' class="active"' : '') + ' href="#">' + (i+1) + '</a></li>');
		}
		$('.slide-buttons').find('a').click(function(e) {
			nr = parseInt($(this).html());
			Slider.slide(nr, false);
		});
		Slider.timeoutId = setTimeout("Slider.slide(2, true)",5000);
		setTimeout("Slider.logoSlide()",8000);
		
		$(".slide-inner").mouseenter(function(){
		    clearTimeout(Slider.timeoutId);
		}).mouseleave(function(){
		    Slider.timeoutId = setTimeout(function(){ Slider.slide(Slider.next_nr, true) }, 5000); 
		});
		//console.log(Slider.element_width);
	},
	slide: function(nr, auto) {
		$('.slide-buttons').find('a').removeClass('active');
		$('.slide-buttons').find('a').each(function() {
			if (parseInt($(this).html()) == nr) $(this).addClass('active');
		});
		visible = Slider.visible_area / Slider.element_width;	
		margin = (nr-1) * Slider.element_width + ($(window).width() < 768 ? 0 : 20);
		
		$('.slide-inner').fadeOut('fast', function() {
			margin = '-' + margin + 'px';
			$('.slide-inner').css('margin-left', margin);
			$('.slide-inner').fadeIn('slow');
		});
		if (Slider.total_elements == nr) Slider.next_nr = 1; else Slider.next_nr = nr + 1;
		if (auto) Slider.timeoutId = setTimeout("Slider.slide(Slider.next_nr, true)",5000);
	},
	logoSlide: function() {

		$('.interactive:visible').each(function() {
			if ($(this).parent().find('.media').is(":not(:animated)")) {
				$(this).fadeOut('slow', function() {
					$(this).hide();
					$('.media').fadeIn('slow');
				});
			}
		});
		$('.media:visible').each(function() {
			if ($(this).parent().find('.interactive').is(":not(:animated)")) {
				$(this).fadeOut('slow', function() {
					$(this).hide();
					$('.interactive').fadeIn('slow');
				});
			}
		});
		setTimeout("Slider.logoSlide()",5000);
	}
}
var Projects = {
	init: function(first_time) {
		new_browser_width = $(window).width(); 
		if (new_browser_width < 520) {
			$('#top-products').hide();
			$('#products').hide();
			$('#top-slide').hide();
			$('.price-slider').hide();
		} else {
			$('#top-products').show();
			$('#products').show();
			$('#top-slide').show();
			$('.price-slider').show();
		}

		projects_line_width = $('.projects').width();
		projects_per_line = Math.floor(projects_line_width / 215);

		

		if ($('#top-products').find('li').length < projects_per_line) {
			to_take = projects_per_line - $('#top-products').find('li').length;
			$('#products').find('li').each(function(i, item) {
				if (i < to_take) {
					$('#top-products').find('ul').append('<li>' + $(this).html() + '</li>');
					$(this).remove();
					if (to_take == i+1) {
						$('#products').find('ul').masonry( 'reloadItems' );
						$('#top-products').find('ul').masonry( 'reloadItems' );
					}
				}
			});
		} else {
			current_per_line = $('#top-products').find('li').length;
			$('#top-products').find('li').each(function(i, item) {
				if ((i+1) > projects_per_line) {
					$('#products').find('ul').prepend('<li>' + $(this).html() + '</li>');
					$(this).remove();
					//console.log(current_per_line + ' and ' + (i+1));
					if (current_per_line == i+1) {
						//console.log('ok: mason');
						$('#products').find('ul').masonry( 'reloadItems' );
						$('#top-products').find('ul').masonry( 'reloadItems' );
					}
				}
			});
		}

		$('.projects').find('li').each(function(i, item) {
			if (!((i+1) % (projects_per_line))) {
				$(this).find('.project-info').css('right', '217px');
			}
		});

		
		//if (first_time) {
			Projects.initProject();
		//}
		
		$(window).unbind('resize');
		$(window).resize(function() {
			Projects.init(false);
			
		});
	},
	initProject: function() {
		$('#products').find('ul').masonry({
			itemSelector : 'li',
			isFitWidth: true,
			isAnimated: true
		});
		$('#top-products').find('ul').masonry({
			itemSelector : 'li',
			isFitWidth: true,
			isAnimated: true
		});
		$("ul.projects a").hover(function() {
			var thumbOver = $(this).parent().find("img").attr("src");
			$(this).css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
			$(this).find(".project-overlay").stop().fadeTo('normal', 0);
			$(this).find("span").stop().fadeTo('slow', 0);
			$(this).parent().find('.project-info').show();
		} , function() { 
			if (!$('#project-outer').is(':visible')) {
				$(this).find(".project-overlay").stop().fadeTo('normal', 0.67);
				$(this).find("span").stop().fadeTo('slow', 1).show();
				$(this).parent().find('.project-info').hide();
			}
		});
		$('.projects').find('li').find('a').click(function(e) {
			var current_project = $(this).attr('rel');
			$(this).parent().addClass('active');
			$('#overlay').fadeIn(function() {
				$('#overlay').css('filter', 'alpha(opacity=75)');
				$('#project-outer').show();
				window_height = $(window).height();
				project_height = $('#project-outer').height();
				$('#project-outer').css('top', (((window_height - project_height) / 2) + $(window).scrollTop()) + 'px');
				Projects.loadProject(current_project);
			});
			e.preventDefault();
		});
		$('.close-project').click(function(e){
			$('#project-outer').hide();
			$('#overlay').fadeOut();
			$('.project-info').hide();
			Projects.resestProjects();
			e.preventDefault();
		});
		$(document).unbind("keydown");
		$(document).keydown(function(e){
		    if (e.keyCode == 27) { 
		    	$('#project-outer').hide();
				$('#overlay').fadeOut();
				$('.project-info').hide();
				Projects.resestProjects();
				e.preventDefault();
		    }
		});
	},
	resestProjects: function() {
		$('.projects').find('.active').each(function() {
			$(this).removeClass('active');
			$(this).find("a").find(".project-overlay").stop().fadeTo('normal', 0.67);
			$(this).find("a").find("span").stop().fadeTo('slow', 1).show();
		});
	},
	loadProject: function(project) {
		$('#project-pic-container').hide();
		$('.ajax-loader').show();
		url = 'projects.php?project=' + project;
		$.ajax({
			type: "GET",
			url: url,
			dataType: "JSON",
			success: function(result) {
				$('#project_name').html(result.current.name);
				$('#project_type').html(result.current.type);
				$('#project_link').html(result.current.homepage).attr('href', result.current.homepage);
				$('.next-project').find('a').unbind('click');
				$('.prev-project').find('a').unbind('click');
				$('.next-project').find('a').click(function(e) {
					Projects.loadProject(result.next.alias);
					$(this).unbind('click');
					Projects.resestProjects();
					e.preventDefault();
				});
				$('.prev-project').find('a').click(function(e) {
					Projects.loadProject(result.prev.alias);
					$(this).unbind('click');
					Projects.resestProjects();
					e.preventDefault();
				});
				Projects.initImages(result.current.images);
			}
		});
	},
	initImages: function(images) {
		browser_width = $(window).width(); 
		if (browser_width < 625) {
			Projects.slider_width = 480;
		} else {
			Projects.slider_width = 615;
			if (browser_width < 1000) {
				Projects.slider_container_width = ((browser_width+51)/768)*615;
			} else 
				Projects.slider_container_width = 615;
		}
		//console.log('browser: ' + browser_width + 'slider:' + Projects.slider_container_width);
		Projects.margin_left = (browser_width - Projects.slider_container_width) / 2 - 5;
		$('#project-pic-container').html('');
		$('#project-pic-container').width((Projects.slider_width+10)*(images.length));
		$('#pr-slider-buttons').html('');
		$('#project_image').removeAttr('class');
		i = 0;
		$.each(images, function(name, image) {
			$('#project-pic-container').append('<div class="project-pic"><img src="' + image + '" alt="" /><div class="project-pic-overlay">&nbsp;</div></div>');
			$('#pr-slider-buttons').append('<li><a' + (i == 0 ? ' class="active"' : '') + ' href="#">' + name + '</a></li>');
			i++;
		});
		$('#project-pic-container').css('margin-left', Projects.margin_left);
		//console.log('margin: ' + Projects.margin_left);
		if (!$.browser.msie && supports_canvas()) {
			images_loaded = false;
			all_images_loaded = false;
			$('.project-pic').each(function(i, container) {
				$(this).find('img:first').load(function() {
					if ($(this).next().html()) { 
						var el = $(this);
						if (this.width > Projects.slider_width) {
							new_width = Projects.slider_width;
							diff = this.width / new_width;
							new_height = this.height / diff;
						} else if (this.height > 450) {
							new_height = 450;
							diff = this.height / new_height;
							new_width = this.width / diff;
						} else {
							new_width = this.width;
							new_height = this.height;
						}
						padding_left = ((Projects.slider_width - new_width) / 2);
						
						if (new_height < 450) {
							padding_top = ((450 - new_height) / 2);
						} else {
							padding_top = 0;
						}
						$(this).width(new_width);
						$(this).height(new_height);
						$(container).find('.project-pic-overlay').css({"margin-left":(padding_left<0?0:padding_left),"margin-top":padding_top,width:new_width,height:new_height});
						if (!$.browser.msie && supports_canvas()) {
							$(this).css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"100","opacity":"0"}).insertBefore(el).queue(function(){
								$(this).parent().css({"padding-top":padding_top});
								$(this).dequeue();
								$(this).css("margin-left",padding_left);
								$(this).next().css("margin-left",padding_left);
								$(this).next().attr('src', grayscale(this.src));
							});
						} else {
							$(this).parent().css({"padding-left":padding_left, "padding-top":padding_top});
						}
						if ((i+1) == $('.project-pic').length) {
							$('.project-pic').find('img:first').fadeIn(300);
							Projects.initGallery(1);
							$('#project-pic-container').show();
							$('.ajax-loader').hide();
							return true;
						}
					}
				});
			});
		} else {
			$('#project-pic-container img').each(function(i, item) {
				 setTimeout(function(){ 
					
					if (this.width > Projects.slider_width) {
						new_width = Projects.slider_width;
						diff = this.width / new_width;
						new_height = this.height / diff;
					} else if (this.height > 450) {
						new_height = 450;
						diff = this.height / new_height;
						new_width = this.width / diff;
					} else {
						new_width = this.width;
						new_height = this.height;
					}
					//console.log($(this).attr('src'));
					//console.log($(this).width() + ' ja ' + $(this).height());
					padding_left = ((Projects.slider_width - new_width) / 2);
					
					if (new_height < 450) {
						padding_top = ((450 - new_height) / 2);
					} else {
						padding_top = 0;
					}
					$(this).width(new_width);
					$(this).height(new_height);
					$(this).parent().find('.project-pic-overlay').css({"margin-left":(padding_left<0?0:padding_left),"margin-top":padding_top,width:new_width,height:new_height});

					if ((i+1) == $('.project-pic').length) { 
						$('#project-pic-container').show();
						$('.ajax-loader').hide();
					}

				}, 1000);
			});
			Projects.initGallery(1);
		}

	},
	makeGrayScale: function() {
		$('.project-pic').stop().each(function(j) {
			$(this).find('.img_grayscale').load(function() {
				//console.log(j+1 + ' ja ' + $('.project-pic').length);
				if ((j+1) == $('.project-pic').length) { 
					Projects.initGallery(1);
					$('#project-pic-container').show();
					$('.ajax-loader').hide();
					return true;
				}
			});
			if (j != 0) $(this).fadeIn(300); else $(this).css('opacity', 0);
		});
	},
	initGallery: function(position) {
		$('.project-pic').each(function(i) {
			if (i+1 == position) {
				$(this).find('.project-pic-overlay').hide(); 
				$(this).find('img').stop().animate({opacity:1}, 300);
				$('.image-zoom').find('a').attr('href', $(this).find('.img_grayscale').attr('src'));
			} else {
				$(this).find('.project-pic-overlay').show();
				$(this).find('.img_grayscale').stop().animate({opacity:0}, 300);
				$(this).find('.project-pic-overlay').css('filter', 'alpha(opacity=75)');
			}
		});
		margin_left = Projects.margin_left - ((position-1)*(Projects.slider_width+10));
		$('.next-image').find('a').unbind('click');
		$('.prev-image').find('a').unbind('click');
		$('#pr-slider-buttons').find('li').unbind('click');
		$('#project-pic-container').stop().animate( { marginLeft: (margin_left) }, 'slow' , function() {
			if (position == 1) $('.prev-image').hide(); else $('.prev-image').show();
			if (position == $('.project-pic').length) $('.next-image').hide(); else $('.next-image').show();
		});
		$('#pr-slider-buttons').find('li').each(function(i) {
			if (i+1 == position) { 
				$(this).find('a').addClass('active');
				if ($(this).find('a').html() != parseInt($(this).find('a').html())) {
					$('#project_type').html($(this).find('a').html());
				}
			} else { 
				$(this).find('a').removeClass('active');
			}
			$(this).find('a').click(function(e) {
				$('#pr-slider-buttons').find('a').removeClass('active');
				$(this).addClass('active');
				position = i+1;
				e.preventDefault();
				$('.next-image').hide();
				$('.prev-image').hide();
				Projects.initGallery(position);
			});
		});
		$(document).unbind("keydown");
		$(document).keydown(function(e){
		    if (e.keyCode == 37) { 
		    	$('.next-image').hide();
				$('.prev-image').hide();
				if (position > 1) Projects.initGallery(position-1);
		    	return false;
		    }
		    if (e.keyCode == 39) {
		    	$('.next-image').hide();
				$('.prev-image').hide();
				if (position < $('.project-pic').length) Projects.initGallery(position+1); 
		    	return false;
		    }
			if (e.keyCode == 27) { 
		    	$('#project-outer').hide();
				$('#overlay').fadeOut();
				Projects.resestProjects();
				e.preventDefault();
		    }
		});
		$('#speech-input').bind('webkitspeechchange', function() {
			if ($('#speech-input').val() == 'left') {
				$('.next-image').hide();
				$('.prev-image').hide();
				if (position > 1) Projects.initGallery(position-1);
		    	return false;
			} else if ($('#speech-input').val() == 'right') {
				$('.next-image').hide();
				$('.prev-image').hide();
				if (position < $('.project-pic').length) Projects.initGallery(position+1); 
		    	return false;
			} else if ($('#speech-input').val() == 'close' || $('#speech-input').val() == 'close') {
				$('#project-outer').hide();
				$('#overlay').fadeOut();
				Projects.resestProjects();
				e.preventDefault();
			}
		});
		$('.next-image').find('a').click(function(e) {
			e.preventDefault();
			$('.next-image').hide();
			$('.prev-image').hide();
			Projects.initGallery(position+1);
		});
		$('.prev-image').find('a').click(function(e) {
			e.preventDefault();
			$('.next-image').hide();
			$('.prev-image').hide();
			Projects.initGallery(position-1);
		});
	}
}
var Navi = {
	init: function(first) {
		$(window).scroll(function() {
			if (window.pageYOffset+700 > $('#contact-area').offset().top) {
				$('#navi').find('li').removeClass('active');
				$('#navi').find('.contact').parent().addClass('active');
			} else if (window.pageYOffset-200 < 0) {
				$('#navi').find('li').removeClass('active');
				$('#navi').find('li:first').addClass('active');
			} else if (window.pageYOffset+200 > $('#features').offset().top) {
				$('#navi').find('li').removeClass('active');
				$('#navi').find('.service').parent().addClass('active');
			}
		});
		if (first) {
			$('.checkout').click(function(e) {
				e.preventDefault();
				$('html, body').animate( { scrollTop: $('#features').offset().top }, 'slow' );
			});
			$('.back-to-top').click(function(e) {
				e.preventDefault();
				$('html, body').animate( { scrollTop: 0 }, 'slow' );
			});
			$('.interactive').click(function(e) {
				e.preventDefault();
				$('html, body').animate( { scrollTop: 0 }, 'slow' );
			});
			$('.media').click(function(e) {
				e.preventDefault();
				$('html, body').animate( { scrollTop: 0 }, 'slow' );
			});
			$('.btn-ask-offer').click(function(e) {
				e.preventDefault();
				$('html, body').animate( { scrollTop: $('#contact-area').offset().top }, 'slow' );
			});
			$('.adbutton').mouseenter(function(e) {
				$(this).parent().animate( { right: 0 }, 'fast' );
				$(this).addClass('active');
			});
			$('#ads').mouseleave(function(e) {
				$(this).animate( { right: -385 }, 'fast' );
				$(this).find('a').removeClass('active');
			});
			Navi.navi();
		}
	},
	navi: function() {
		$('#navi').find('li').each(function() {
			li = $(this);
			li.find('a').click(function(e) {
				if (!$(this).hasClass('facebook')) {
					$(window).unbind('scroll');
					$('#navi').find('li').removeClass('active');
					$(this).parent().addClass('active');
					element = $(this).attr('href').replace('#', '');
					$('.adbutton').attr('href', '#' + element);
					if (element) {
						var scroll = $('#' + element).offset().top; 
					} else { 
						var scroll = 0;
					}
					$('html, body').animate( { scrollTop: scroll }, 'slow', function() {
						Navi.init(false);
					});
					e.preventDefault();
				}
				
			});
			$(this).find('a').mouseenter(function(e) {
				$(this).css('left', 0);
				$(this).animate( { left: -120 }, 'fast' );
			});
			$(this).find('a').mouseleave(function(e) {
				$(this).animate( { left: 0 }, 'fast' );
			});
		});
	}
}
$(function() {
	Navi.init(true);
	Slider.init();
	Projects.init(true);
	Form.init();
	$("a[rel^='prettyPhoto']").prettyPhoto();
	
	$('.open-in-new').click(function() {
        window.open(this.href);
        return false;
    });
	
/* google analytics code */
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-13269893-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
	
});
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 supports_canvas() {
  browser_width = $(window).width(); 
  if (browser_width < 625) return false;
  return !!document.createElement('canvas').getContext;
}
