/* Document Load */
jQuery(document).ready(function() {
	Menu.Init();
	News.Init();
	Comments.Init();
	
	setButtons();
	setOpacity();
	
	Form.init();
	Form.initLink();
	

	jQuery('#searchSite').bind('focus',function(){
		var val = jQuery(this).val();
		if (val == 'поиск:') jQuery(this).val('')
		if (val == '') jQuery(this).val('поиск:')
	});
	jQuery('#searchSite').bind('blur',function(){
		var val = jQuery(this).val();
		if (val == 'поиск:') jQuery(this).val('')
		if (val == '') jQuery(this).val('поиск:')
	});

	
});




/**
 *  Form namespace 
 */
 
var Form = {version	: '0.0.2'
	  
	, initLink : function () {
		var formLinks = jQuery('.formLink')
		formLinks.unbind('click');
		formLinks.click(function(){Form.show(this.href);return false;});
	return true;}
	  
	, init : function () {
		var codeimageChanges = jQuery('.codeimageChange', jQuery('#orderForm'));
		codeimageChanges.unbind('click');
		codeimageChanges.bind('click',function(){
			Form.refreshCodeImage();
		return false;});
		jQuery('#orderButton').unbind('click');
		jQuery('#orderButton').bind('click',function(){
			Form.send();
		return false;});
	return true;} 
	
	, refreshCodeImage : function () {
		jQuery('#codeimageChangeable').attr('src','codeimage/' + Math.random());
	return true;} 
	
	  
	, checkmail : function (email) { 
		dog = email.indexOf("@"); 
		if (dog == -1) return false; 
		if (email.indexOf(".") == -1) return false; 
		if ((dog < 1) || (dog > email.length - 5)) return false;  
		if ((email.charAt(dog - 1) == '.') || (email.charAt(dog + 1) == '.')) return false; 
	return true;} 
	
	, check : function (form) { 
	
		var error = 0;
	
		jQuery('.check-simple', jQuery(form)).each(function(){
			var currentId = jQuery(this).attr('id');
			jQuery('#'+ currentId +'-error').html('');
			if 	((jQuery(this).val() == '') ||
				(jQuery(this).html() == '' && jQuery(this).attr('tagName') == 'textarea') ||
				(jQuery(this).attr('type') == 'checkbox' && jQuery(this).attr('checked') == false)) {
				jQuery('#'+ currentId +'-error').html('Заполните данное поле');	
				error++;
			}
		});
		
		jQuery('.check-email', jQuery(form)).each(function(){
			var currentId = jQuery(this).attr('id');
			jQuery('#'+ currentId +'-error').html('');
			if 	(jQuery(this).val() == '') {
				jQuery('#'+ currentId +'-error').html('Заполните данное поле');	
				error++;
			} else if (!Form.checkmail(jQuery(this).val())) {
				jQuery('#'+ currentId +'-error').html('Некорректный email');	
				error++; 
			}
		});
		
		if (error > 0) return false;
		
	return true;}
	
	, show : function (href) {
	
		jQuery.ajax({
		    cache		: true,
		    timeout		: 10000,
		    dataType	: 'html',
		    type		: 'POST',
		    url			: href,
		    data		: {'ajax':'true'},
		    error		: function(){},
		    
		    success: function(response){
			
				createdForm = jQuery('<div class="shadow" id="shadow"></div><div class="middle" id="middle"><div class="middle-0"><div class="middle-1"><div class="middle-2" id="middle2"></div></div></div></div>');
				
				var currentPage = jQuery('#page');
				currentPage.css('z-index','200');
				jQuery('.footer', currentPage).css('z-index','1');
				currentPage.append(createdForm);
				
				var currentShadow = jQuery('#shadow');
				var currentMiddle = jQuery('#middle');
				currentShadow.height(currentPage.height());
				currentMiddle.css('top',Utilites.getBodyScrollTop() + 'px');
				currentMiddle.height(Utilites.getClientHeight());
				//currentShadow.fadeTo('fast','.1',function(){currentShadow.show();});
					currentShadow.css('display','block');
				
					currentMiddle.fadeIn('fast');
					document.getElementById(String('#middle2').replace('#','')).innerHTML = '';
					jQuery('#middle2').html(response);
					Form.placeCloseButton();
					//Form.refreshCodeImage();
					Form.init();
				
		    }
	   	});
	return false;}
	
	, close : function () {	
		jQuery('#middle').fadeOut('slow',function(){ 
			jQuery('#shadow').css('display','none');
		
				jQuery('#shadow').remove(); jQuery('.footer', jQuery('#page')).css('display','block');
				
			});
	}
	
	, placeCloseButton : function () {	
		jQuery('#shadow-form').append('<div id="shadowClose" width="30" height="30" class="shadow-close"></div>');
		jQuery('#shadowClose').unbind('click');
		jQuery('#shadowClose').click(Form.close);
	}
	
	, send : function  () {
		if (!Form.check('#orderForm')) return false;
		Ajax.query (jQuery('#orderForm').attr('action'), '#middle2', jQuery('#orderForm').serialize(), 'POST', true, function (block, response) {
			if (jQuery(response).find('#orderForm').size() > 0) {
				Form.placeCloseButton();
				//Form.refreshCodeImage();
				Form.init();
			} else {
				setTimeout('Form.close();', 4000);
				jQuery('#codeimageChangeableDirector').show();
				//Form.refreshDirectorCodeImage();
				return false;
			}
		},'overlay');
	return false;}

}

/**
 * Set opacity style for elements, which have style like 'opacity-15'
 * 
 * @return bool
 */

function setOpacity () {
	
	jQuery("[class*='opacity']").each(function (i) {
		var opacityValue = this.className.substr(this.className.indexOf('opacity-') + 'opacity-'.length, 2);
		if (jQuery.browser.msie) {
			jQuery(this).css('filter',jQuery(this).css('filter') + ' progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacityValue+')');
		} else {
			jQuery(this).css('opacity','.' + opacityValue);
		}
	});
	
	return true;
}

function setButtons () {
	
	jQuery('button').bind('mouseover', function (i) {
		jQuery(this).addClass('button-hovered');
	});
	jQuery('button').bind('mouseout', function (i) {
		jQuery(this).removeClass('button-hovered');
	});
	
	return true;
}

var Utilites = {		
	  version : '0.0.1'
	  
	, scrollToContent : function () {
		window.scrollTo(0,231);
	}
		, getBodyScrollTop : function () {
		return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
	}
	
	, getClientHeight : function () {
		return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
	}
}

/* Common */
	/* Repair IE footer bug */
	repairTroubleWithJS = function () {
		document.body.style.fontSize = 68 + Math.random()/6 + 0.75 + '%';
	}
	/* Refresh code */
	refreshCodeImage = function () {
		jQuery('#codeimageChangeable').attr('src', 'codeimage/'+Math.random());
	}
	/* Print page */
	printit = function () {
		if(window.print) window.print(); return false;
		var WebBrowser = '<object id="WebBrowserPrint" width="0" height="0" classid="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowserPrint.ExecWB(6, 2);
	}
	/* Check Email */
	checkmail = function (email) { 
		var at = email.indexOf("@"); 
		if (at == -1) return false; 
		if (email.indexOf(".") == -1) return false; 
		if ((at < 1) || (at > email.length - 5)) return false;  
		if ((email.charAt(at - 1) == '.') || (email.charAt(at + 1) == '.')) return false; 
		return true;
	} 
	/* Pages */
	function go (goHref, goBlock) {
		MyUserFunction = repairTroubleWithJS;
		
		jQuery('#pages').html('<img src="templates/common/images/ajax.gif" alt="loading..." />');

		if (goHref.search(/poll/i) != -1) {
			Ajax.query (goHref, '#'+goBlock, '', 'POST', true, function (block, response) {
				News.Init();
			}, jQuery('#'.goBlock).html());
		} else {
			Ajax.query (goHref, '#'+goBlock, '', 'POST', false, function (block, response) {
				News.Init();
			}, jQuery('#'.goBlock).html());
		}
		
		
	}


/* Text tabs function */
	function hideTabElement(id) {jQuery('#'+id).css('display', 'none');}
	
	function hideAllTabElements() 
	{
		jQuery('.tab-text').each(function() {
			this.style.display = 'none';
			jQuery('#link-'+this.id).attr('class', '');
		});
	}
	
	function toggleTabElement(id)
	{
		hideAllTabElements();
		if (jQuery('#'+id).css('display') == 'none') {
			jQuery('#'+id).css('display', '');
			jQuery('#link-'+id).attr('class', 'link-hovered');
		} else {
			jQuery('#'+id).css('display', 'none');
			jQuery('#link-'+id).attr('class', '');
		}
	}

/* News */
var News = {

	  version	: '0.0.1'
	
	, preloader : '<img src="templates/common/images/ajax.gif" alt="..." />'
	  
	, Init : function() {
		jQuery('.newsFiltersItem').bind('click', function() {
			jQuery('#yearNews').html(News.preloader);
			Ajax.query (this.href, '#newsblock', '', 'POST', false, function (block, response) {
				News.Init();
			}, jQuery('#newsblock').html());
			return false;
		});  
	}

}

/* Menu */
var Menu = {

	  version	: '0.0.1'
	
	, menuTimeOut : 0
	, menuTimeOutMS : 3000
	, bulletTimeOut : 100
	
	, Init : function() {
		jQuery('.menu-item').bind('mouseover', function() {
			jQuery('.submenu').filter('[id!='+this.id+'-submenu]').hide();
			if (jQuery('#' + this.id + '-submenu').css('display') == 'none') {
				jQuery('#' + this.id + '-submenu').fadeIn();
				clearTimeout(Menu.menuTimeOut);
			}
		});
		jQuery('.menu-item').bind('mouseout', function() {
			Menu.menuTimeOut = setTimeout("jQuery('#" + this.id + "-submenu').fadeOut('slow');  ", Menu.menuTimeOutMS);
		});
		jQuery('.submenu').bind('mouseout', function() {
			Menu.menuTimeOut = setTimeout("jQuery('#" + this.id + "').fadeOut('slow'); ", Menu.menuTimeOutMS);
		});
		jQuery('.submenu').bind('mouseover', function() {
			clearTimeout(Menu.menuTimeOut);
		});
		jQuery('.submenu a').bind('mouseover', function() {
			clearTimeout(Menu.menuTimeOut);
		});
		return true;
	}
}


/* Forms */
/*
var Form = {
	  version : '0.0.1'
	  
	, Validate : function() {
		var error = 0;
				
		jQuery('.xformsValidateEmpty').each(function() {
			var currentId = (this.id).split('-')[1];
			
			jQuery('#error-'+currentId).html('');
			
			if(	(jQuery('#xfield-'+currentId).tagName 	== 'textarea' && jQuery('#xfield-'+currentId).html() == '')	||
			   	(jQuery('#xfield-'+currentId).type 		== 'checkbox' && !jQuery('#xfield-'+currentId).checked)		||
		   		(jQuery('#xfield-'+currentId).val() 	== '')) {
		 		
		 		jQuery('#error-'+currentId).html('заполните данное поле');
		 		
		 		error++;
		 	}
		});
		
		jQuery('.xformsValidateEmail').each(function() {
			var currentId = (this.id).split('-')[1];
			
			if(jQuery('#xfield-'+currentId).val() != '') {
				
				jQuery('#error-'+currentId).html('');
				
				if(checkmail(jQuery('#xfield-'+currentId).val()) == false) {
					jQuery('#error-'+currentId).html('некорректный email');
					error++;
				} 
			}
		});
	
		if (error > 0) {
			return false;
		}
		
		return true; 	
	}
}
*/
/* Ajax handler */	
var Ajax = {
		
	  version			: 	'0.0.1'
	  
	, preloader			:	''
	
	, preloaderInterval	:	''
	
	, preloaderImage	:	'&nbsp;'
	
	, method	:	'POST'
	
	, treads	:	new Object()
	
	, query	:	function (href, block, data, method, noCache, callback, preloader) {
				
		if (Cache.is(href + data) && !noCache) {
			response = Cache.get(href + data);
		
			if (block != '') {
				jQuery(block).html(response);
				if (!preloader) {
					Utilites.scrollToContent();
				}
			}
			if (typeof callback == 'function') {
				callback(block, response);
			}
			return true;
		} 		
		if (Ajax.treads[href + data] != undefined && Ajax.treads[href + data] != false) {
			return true;		
		} else {
			Ajax.treads[href + data] = true;
		}
		
		if (preloader || href == 'authline') {
			if (block != '') {
				jQuery(block).html(preloader);
			}
		} else if (block != ''){
			
		}
		
		preloader 	= (!preloader) 	? Ajax.preloader 	: preloader;
		method 		= (!method) 	? Ajax.method 		: method;
		
		jQuery.ajax({
			cache		: true,
			timeout		: 10000,
			dataType	: 'html',
			type		: method,
			url			: href,
			data		: data + '&ajax=true',
	
			success: function(response){
				Ajax.treads[href + data] = false;
				if (!noCache){
					Cache.put(href + data, response);
				}
				if (block != '') {
					jQuery(block).html(response);
				}
				if (typeof callback == 'function') {
					callback(block, response);
				}
				return true;
			}
		});
		
		return true;
	}
}
	
	
/* Cache handler */	

var Cache = {

	  version	: 	'0.0.1'
		
	, cacheData : new Object()
	 
		, get 		: function (href) {
		return Cache.cacheData[href];
	}
	
	, is 		: function (href) {
		if (Cache.cacheData[href] != undefined && Cache.cacheData[href] != '') {
			return true;		
		}
		return false;
	}
	
	, put 		: function (href, content) {
		Cache.cacheData[href] = content;
		return true;
	}
	
	, remove	: function (href) {
		Cache.cacheData[href] = '';
		return true;
	}
}

/* Poll */

	function poll (id) {
	
		if (!id) {id = '';}
		
		data = '&pollside=true';
		data = data + '&pollid='+id;
		
		if (jQuery('#pollbutton'+id).size() > 0) {

			data = data + '&p_id='+jQuery('#p_id'+id).val();
			data = data + '&qoa='+jQuery('#qoa'+id).val();

			var elements = document.getElementById('form_poll'+id).elements;
			for (var i = 0; i < elements.length; i++) {
				switch (elements[i].type.toLowerCase()) {
					case 'checkbox':
					case 'radio':
						if (elements[i].checked)
							data = data + '&'+elements[i].name + '=' + elements[i].value;
				}
			}
			jQuery('#pollbutton'+id).html('<img src="templates/common/images/ajax.gif" alt="..." />');
		}
		
		Ajax.query ('side_poll', '#side_poll' + id, data, 'POST', true, function (block, response) {}, jQuery('#side_poll'+id).html());
	}

    
/* Comments */
var Comments = {
	  version : '0.0.1'
	  
	, Init : function() {
		jQuery('#commentFormIn').bind('submit',function(){
			jQuery('.form-error').html('&nbsp;');
			
			var error = 0;
			
			if (jQuery('#name').val() === '' ) {
				error++;
				jQuery('#error-name').html('введите ваше имя');
			}

			if (jQuery('#comment').val() == '' ) {
				error++;
				jQuery('#error-comment').html('введите ваш комментарий');
			}
			
			data  = '&name=' + jQuery('#name').val();
			data += '&comment=' + jQuery('#comment').val();
			data += '&askImage=' + jQuery('#askImage').val();
			
			if (error == 0) {
				jQuery('#commentButton').html('<img src="templates/common/images/ajax.gif" alt="..." />');
				Ajax.query (jQuery(this).attr('action'), '#commentForm', data, 'POST', true, function (block, response) {
					Comments.Init();
				}, jQuery('#commentForm').html());
			} 
			
		return false;});
	}
	  
	, Validate : function() {
		var error = 0;
				
		jQuery('.xformsValidateEmpty').each(function() {
			var currentId = (this.id).split('-')[1];
			
			jQuery('#error-'+currentId).html('');
			
			if(	(jQuery('#xfield-'+currentId).tagName 	== 'textarea' && jQuery('#xfield-'+currentId).val() == '')	||
			   	(jQuery('#xfield-'+currentId).type 		== 'checkbox' && !jQuery('#xfield-'+currentId).checked)		||
		   		(jQuery('#xfield-'+currentId).val() 	== '')) {
		 		
		 		jQuery('#error-'+currentId).html('заполните данное поле');
		 		
		 		error++;
		 	}
		});
		
		jQuery('.xformsValidateEmail').each(function() {
			var currentId = (this.id).split('-')[1];
			
			if(jQuery('#xfield-'+currentId).val() != '') {
				
				jQuery('#error-'+currentId).html('');
				
				if(checkmail(jQuery('#xfield-'+currentId).val()) == false) {
					jQuery('#error-'+currentId).html('некорректный email');
					error++;
				} 
			}
		});
	
		if (error > 0) {
			return false;
		}
		
		return true; 	
	}
}
