/*
 * Outputs email address using javascript to protect from spiders
 */

var emailHost = 'av-arch.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;
}

/**
 * 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;
	};
};

/*
 * 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,"");
};

// 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();
		}
		});
	}
}

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;
}