/*
 * Outputs email address using javascript to protect from spiders
 */

var emailHost = 'videinfra.com';
var emailE = {riga: 'info', moscow: 'moscow', sydney: 'sydney', cv: 'cv'};

$(document).ready(function () {

	/**
 	  * Banner hover effect
 	  */
	$('div.banner_type_1').each(function (k, v) {
		$(v).mouseover(function () {	$(this).addClass('hover'); });
		$(v).mouseout(function () {		$(this).removeClass('hover'); });
	});
});

/**
 * Outputs email address
 * 
 * @param {String} email_e Valid values are: 'riga', 'moscow', 'sydney', 'cv'
 */
function outputEmail(email_e)
{
	if (emailE[email_e])
	{
		var addrLink  = 'mailto:' + emailE[email_e] + '@' + emailHost;
		var addrTitle = emailE[email_e] + '&#64;' + emailHost;
		document.write('<a href="' + addrLink + '">' + addrTitle + '</a>');
	}
} 

function getUrlHash()
{
	var url_hash = document.location.href;
	var pos = url_hash.indexOf('#');
		
	if (pos != -1)
	{
		return url_hash.substr(pos + 1);
	}
	
	return false;
}
function setUrlHash(url_hash)
{
	var url = document.location.href;
	var pos = url.indexOf('#');
		
	if (pos != -1)
	{
		url = url.substr(0, pos);
	}
	
	document.location.href = url + '#' + url_hash;
}

/**
 * Tracks mouse position and executed $tickFunction every $tick milliseconds if mouse is
 * moved and left button is down
 * 
 * @param {object} element Element for which mouse position will be tracked
 * @param {function} tickFunction Function, which is used as callback, if mouse is moved
 * @param {integer} tick Number of miliseconds between tickFunction calls
 */
function DragTracker (element, tickFunction, tick)
{
	this.element = $(element);
	this.func = tickFunction;
	this.mouseIsDown = false;
	this.pos = {x: 0, y: 0};
	this.change = {x: 0, y: 0};
	
	var _self = this;
	this.init(tick);
}

DragTracker.prototype.init = function (tick) {
	var _self = this;
	if (!tick || tick == undefined) tick = 32;
	
	/* onMouseDown, save currect mouse position */
	this.element.mousedown(function(e) {
		_self.mouseIsDown = true;
		
		_self.pos.x = e.pageX;
		_self.pos.y = e.pageY;
		_self.change.x = 0;
		_self.change.y = 0;
	});
	/* onMouseUp save mouse position, calculate difference and call callback function */
	$(document).mouseup(function(e) {
		if (_self.mouseIsDown)
		{		
			_self.change.x += e.pageX - _self.pos.x;
			_self.change.y += e.pageY - _self.pos.y;
			
			_self.pos.x = e.pageX;
			_self.pos.y = e.pageY;
			
			_self.mouseIsDown = false;
			_self.func(_self.change, 'mouseup');
			
			_self.change.x = 0;
			_self.change.y = 0;
		}
	});
	/* onMouseMove save mouse position and calculate difference */
	$(document).mousemove(function(e) {
		if (_self.mouseIsDown)
		{
			_self.change.x += e.pageX - _self.pos.x;
			_self.change.y += e.pageY - _self.pos.y;
			
			_self.pos.x = e.pageX;
			_self.pos.y = e.pageY;
		}
	});
	
	var _tick = tick;
	
	/* After 'tick' milliseconds call callback function passing mouse position change since last callback */
	setInterval(function () {
		if (_self.mouseIsDown)
		{
			_self.func(_self.change, 'mousemove');
			
			_self.change.x = 0;
			_self.change.y = 0;
		}
	}, tick);
};

/**
 * Footer popup
 * Shows popup using vertical slideIn. Popup after opening is positioned above the callee,
 * so that callee is in the vertical middle of the popup.
 */

function Popup (selector) {
	this.element = $(selector).eq(0);					/* Popup container element */
	this.element_back = $('div', this.element).eq(0);	/* Content element */
	this.state   = 0;									/* State: 0 - hidden, 1 - visible*/
	this.running = false;								/* Animation is running */
	this.maxMarginTop = -1;								/* How much px popup will move up */
	this.duration = 500;								/* Animation duration */
	
	this._init();
}
/**
 * Show popup
 */
Popup.prototype.show = function () {
	if (!this.state && !this.running)
	{
		this.running = true;
		
		if (this.maxMarginTop == -1)
		{
			/* Calculate popup height (vertical position), animation duration and save them */
			
			this.maxMarginTop = - Math.floor(this.element.height() / 2) - 10;
			
			/* Popup must not be lower than callee + 200px */
			if (this.maxMarginTop < -200)
			{
				this.maxMarginTop = 2 * this.maxMarginTop + 200;
				this.duration = - Math.floor(this.maxMarginTop * 2.5);
			}
			
			this.element_back.css({display: 'none'});
		}
		
		this.state = 1;
		this.element.css({marginTop: '0'});
		
		var _self = this;
		
		jQuery.synchronize.start();
			this.element.animate({marginTop: this.maxMarginTop + 'px'}, {duration: this.duration});
			this.element_back.slideDown(this.duration, function () {
				_self.running = false;
			});
		jQuery.synchronize.end();
		
		this.element_back.css({opacity: 0.9});
	}
};
/**
 * Hide popup
 */
Popup.prototype.hide = function () {
	if (this.state && !this.running)
	{
		var _self = this;
		
		this.state = 0;
		this.running = true;
		
		jQuery.synchronize.start();
			this.element.animate({marginTop: '0px'}, {duration: this.duration});
			this.element_back.slideUp(this.duration, function () {
				_self.element.css({marginTop: '-2000px'});
				_self.running = false;
			});
		jQuery.synchronize.end();
	}
};
/**
 * Toggle show/hide
 */
Popup.prototype.toggle = function () {
	if (!this.state)
		this.show();
	else
		this.hide();
};
/**
 * Class constructor
 */
Popup.prototype._init = function () {
	var _self = this;
	$(document).click (function() {
		_self.hide();
	});
};



/**
 * Scroller, manipulates horizontally scrollable content
 * 
 * @param {Object} container
 * @param {Object} content
 * @param {Array} elements
 */
function Scroller ()
{
	this.container = null;					/* Container element */
	this.content = null;					/* Content, which will be moved */
	this.elements = null;					/* Content elements of the 'this.content' */
	this.widths = [];						/* Widths of the elements*/
	this.pos = 0;							/* Current content horizontal posittion */
	this.actual_pos = 0;					/* Actual scroller position */
	this.max_pos = 0;						/* Max position of the content */
	this.constantAnimationSpeed = false;	/* Animation time doesn't change */
	this.speedMultiplier = 1;

	/**
	 * Rereads information about scroller container, content and elements
	 * This function must be called before using scrollTo, setPos, scrollToElement
	 * 
	 * @param {Object} container
	 * @param {Object} content
	 * @param {Array} elements
	 */
	this.refresh = function (container, content, elements)
	{
		this.container = $(container);
		this.content = $(content);
		this.elements = elements;
		this.widths = [];
		this.pos = 0;
		this.actual_pos = 0;
		
		var sum = 0;
		var el = null;
		
		this.content.css({marginLeft: '0px'});		

		for(var i = 0, j = this.elements.length; i < j; i++)
		{
			el = $(this.elements[i]);
			this.widths[i] = el.width();
			
			sum += this.widths[i];
		}
		
		sum = sum - this.container.width();
		if (sum < 0) sum = 0;
		
		this.max_pos = sum;
	};
	
	/**
	 * Set scroller position
	 * Pos is offset position in px
	 * 
	 * @param {Integer} pos
	 */
	this.setPos = function (pos)
	{
		pos = this._sanitizePos(pos);
		
		if (pos == this.pos) return;
		if (pos > this.max_pos) pos = this.max_pos;
		
		this.pos = pos;
		this.actual_pos = this.pos;
		this.content.css({marginLeft: - pos + 'px'});
	};
	
	/**
	 * Returns scroller offset position in px
	 * 
	 * @return {Integer}
	 */
	this.getPos = function ()
	{
		return this.pos;
	};

	/**
	 * Scrolls scroller to given position with animation
	 * 
	 * @param {Object} pos
	 */
	this.scrollTo = function (pos)
	{
		var _self = this;
		
		pos = this._sanitizePos(pos);
		if (pos == this.pos) return false;
		
		if (this.constantAnimationSpeed)
		{
			var speed = parseInt(this.constantAnimationSpeed) || 500;
		}
		else
		{
			var dif = Math.abs(this.pos - pos);
			var speed = Math.floor(dif * 2.5) * this.speedMultiplier;
		}
		
		this.content.stop();
		
		this.actual_pos = this.pos;
		this.pos = pos;
		
		this.content.animate({marginLeft: - pos + 'px'}, {duration: speed, complete: function () {
			_self.actual_pos = _self.pos;
		}});
		
		return true;
	};
	
	/**
	 * Scroll scroller to given element
	 * Argument 'element' is an index of the element to which content will be scrolled
	 *  
	 * @param {Object} element
	 */
	this.scrollToElement = function (element)
	{
		if (element > this.widths.length) element = this.widths.length;
		if (element < 0) element = 0;
		
		var sum = 0;
		
		for(var i = 0; i < element; i++)
		{
			sum += this.widths[i];
		}
		this.scrollTo(sum);
	};
	
	/**
	 * Filters position
	 * @param {Integer} pos
	 */
	this._sanitizePos = function (pos)
	{
		pos = parseInt(pos);
		if (pos < 0) pos = 0;
		if (pos > this.max_pos) pos = this.max_pos;
	
		return pos;
	};
};

/* Bubles event, cancels event propagation */
function eventBuble(e)
{
	if (window.event)
		window.event.cancelBubble = true;
	else	
		e.stopPropagation();
}

/*
 * jQuery animation synchronization plugin
 * 
 * Changes to jQuery 1.2.3:
 *		3181: edit	 	function t(gotoEnd, t){
 * 		3182: edit			return self.step(gotoEnd, t);
 * 
 * 		3186: add		t.fx = this;
 * 
 * 		3192: add		var t = (new Date()).getTime();
 * 
 * 		3196: edit		if ( !timers[i](null, t) )
 * 		3197: add		{
 * 		3198: add			timers.fx = null;
 * 
 * 		3200: add		}
 * 
 * 		3236: edit		step: function(gotoEnd, time){
		3237: edit		var t = (time || (new Date()).getTime());
 * 
 * Usage:
 * 		jQuery.synchronize.start();
 * 		$('#el2').animate(...);
 * 		$('#el3').animate(...);
 * 		jQuery.synchronize.end(); 
 * 
 * Bug:
 * 		if animation is added to the queue - synchronizes current animation not the one in queue
 * 		Animations must not be in queue!
 */
jQuery.synchronize = {
	timerQueueFirst: 0,
	start: function () {
		jQuery.synchronize.timerQueueFirst = jQuery.timers.length;
	},
	end: function () {
		var timerQueueFirst = jQuery.synchronize.timerQueueFirst;
		var timerQueueLast = jQuery.timers.length;
		
		if (timerQueueFirst + 1 < timerQueueLast)
		{
			var startTime = jQuery.timers[timerQueueFirst].fx.startTime;
			for (var i = timerQueueFirst + 1; i < timerQueueLast; i++)
			{
				if (jQuery.timers[i])
					jQuery.timers[i].fx.startTime = startTime;
			}
		}
		jQuery.synchronize.timerQueueFirst = 0;
	}
};

String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g,"");
};

/* Initializes footer popup */
$(function () {
	if ($('#projects .popup').size())
	{
		var footerPopup = new Popup('#projects .popup');
		$('#projects .back div:last').addClass('last');
		$('#projects .back div').each(function() {
			$(this).click(function() {
				document.location.href = $('a:first-child', this).attr('href');
			});
		});
		$('#projects .button a').each(function() {
			$(this).click(function () {
				footerPopup.toggle();
				return false;
			});
		});
	}
	
	/* Main menu*/
	if ($('#menu').size())
	{
		$('#menu td').each(function () {
			var el = $(this);
			if (!$(this).hasClass('active'))
			{
				$(this).mouseover(function () { $(this).addClass('hover'); });
				$(this).mouseout(function () { $(this).removeClass('hover'); });
			}
		});
	}
});

// Validates email address
function isValidEmail(email){
  validRegExp = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/i;
  
  if (validRegExp.test(email))
  	return true;
	
  return false; 
}

var sendEmail_sending = false;

// Ajax requests
function sendEmail() {
	if (sendEmail_sending) return;
		
	/* Each inputs previous element is a label, removing class 'error' */
	var subject = 	$('#contact_subject').removeClass('error');
		subject.prev().removeClass('error');
	
	var name    =	$('#contact_name').removeClass('error');
		name.prev().removeClass('error');
	
	var email   = 	$('#contact_email').removeClass('error');
		email.prev().removeClass('error');
	
	var text    = 	$('#contact_comment').removeClass('error');
		text.prev().removeClass('error');
	
	
	var val_subject = subject.val().trim();
	var val_name = name.val().trim();
	var val_email = email.val().trim();
	var val_text = text.val().trim();
	
	if (val_subject == '' || val_name == '' || val_email == '' || !isValidEmail(val_email) || val_text == '')
	{
		if (val_subject == '') 	subject.addClass('error').prev().addClass('error');
		if (val_name == '') 	name.addClass('error').prev().addClass('error');
		if (val_email == '' || !isValidEmail(val_email)) email.addClass('error').prev().addClass('error');
		if (val_text == '') 	text.addClass('error').prev().addClass('error');
	}else{
		sendEmail_sending = true;
		
		$.ajax({
		// AJAX-specified URL
		url: "http://"+document.domain+"/json?action=send_email",
		data: {subject: val_subject, name: val_name, email: val_email, comment: val_text},
		// JSON
		type: "POST",
		dataType : "json",
		// Handle the success event
		// response parser call (it's requried for work php)
		success: function(data, textStatus){
			if (data.error) {
				sendEmail_sending = false;
				error = data.error_msg;
				$([subject, name, email, text]).each(function () { $(this).addClass('error').prev().addClass('error'); });
			}
			else {
				var container 		= $('div.form_container');
				var content_form	= $('div.form_container form');
				var content_thanks	= $('div.form_container .thankyou');
				
				content_thanks.before(content_form).parent().css('marginLeft', '0px');
				$('div.form_container').animate({marginLeft: '-662px'}, function () {
					sendEmail_sending = false;
				});
				
				setTimeout(function () {
					$('#contact_subject').val('');
					$('#contact_name').val('');
					$('#contact_email').val('');
					$('#contact_comment').val('');

					content_form.before(content_thanks);
					container.css({marginLeft: '0px'});
										
					container.animate({marginLeft: '-662px'});
					
				}, 15000);
			}
		},
		error: function () {
			sendEmail_sending = false;
			//On request failure try resending email
			sendEmail();
		}
		});
	}
}

var projectCache = {};
var curProjectId = 0;

function getProject(id, clientName) {
	curProjectId = id;
	if (projectCache[id])
	{
		//Cache
		
		var hiddenInput = document.getElementById('tr_hidden');;
		var activeProject = document.getElementById('tr_'+projectCache[id].id+'');
		var previosActiveProject = document.getElementById('tr_'+hiddenInput.value+'');
		var activeProjectReference = document.getElementById('activeReference');
		var date = document.getElementById('activeDate');

		previosActiveProject.className = '';
		activeProject.className = 'active';
				
		hiddenInput.value = (projectCache[id].id);
		 
		if (projectCache[id].date)
		{
			date.innerHTML = projectCache[id].dateFormated;
			date.className = '';
		}
		else
		{
			date.className = 'hidden';
		}
		if (activeProjectReference) {
			activeProjectReference.href = projectCache[id].referenceFileDir + projectCache[id].referenceFileName;
		}
		if (!projectCache[id].referenceFileName) {
				document.getElementById('reference').className = 'hidden';
		}
		else {
				document.getElementById('reference').className = 'reference';
		}
		document.getElementById('activeName').innerHTML = projectCache[id].nameFromIni;
		document.getElementById('activeDesc').innerHTML = projectCache[id].fullDescription;
	}
	else
	{
		$.ajax({
			// AJAX-specified URL
			url: "http://"+document.domain+"/json?action=getProject&id=2&work_id="+id,
			// JSON
			type: "GET",
			dataType : "json",
			// Handle the success event
			// response parser call (it's requried for work php)
			success: function(data, textStatus){
				projectCache[data.id] = data;
				
				if (curProjectId == data.id)
				{
					//Project data was loaded, but user is already looking at other project
					var date = document.getElementById('activeDate');
					var hiddenInput = document.getElementById('tr_hidden');
					var activeProject = document.getElementById('tr_'+data.id+'');
					var previosActiveProject = document.getElementById('tr_'+hiddenInput.value+'');
					var activeProjectReference = document.getElementById('activeReference');
					previosActiveProject.className = '';
					activeProject.className = 'active';
					if (data.date)
					{
						date.innerHTML = data.dateFormated;
						date.className = '';
					}
					else
					{
						date.className = 'hidden';
					}
					hiddenInput.value = (data.id); 
					//document.getElementById('moreAbout').innerHTML = '<a id="moreLink" href="/portfolio/'+clientName+'/'+data.workURL+'">More about project</a>';
					document.getElementById('activeName').innerHTML = data.nameFromIni;
					document.getElementById('activeDesc').innerHTML = data.fullDescription;
					if (activeProjectReference) {
						activeProjectReference.href = data.referenceFileDir + data.referenceFileName;
					}
					if (!data.referenceFileName) {
						document.getElementById('reference').className = 'hidden';
					}
					else {
						document.getElementById('reference').className = 'reference';
					}	
				}
			}
		});
	}
};

function popupWindow(path, width, height, scrollbars) {
	width = width || 790;
	height = height || 675;
	scrollbars = (scrollbars ? 'yes' : 'no');
	blah = window.open(path, "_blank", "width=" + width + ",height=" + height + ",directories=no,location=no,menubar=no,resizable=no,scrollbars=" + scrollbars + ",status=no,toolbar=no");
	return false;
}