/* Document Load */
jQuery(document).ready(function() {
	Menu.Init();
	Faq.Init();
	News.Init();
		setOpacity();
		
	jQuery('form.prod-select').find('select').change(function(){
		
		data = jQuery('form.prod-select').serialize();
		Ajax.query ('catalogue', '#position', data, 'POST', true, function (block, response) {
		}, jQuery('#position').html());	
	})
});

var Utilites = {		
	  version : '0.0.1'
	  
	, scrollToContent : function () {
		window.scrollTo(0,231);
	}
}

/**
 * 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);
		jQuery(this).css('opacity','.' + opacityValue);
		jQuery(this).css('filter','Alpha(opacity=' + opacityValue+')');
	});
	
	return true;
}

function openWindow(url, width, height)
	{
		var left = Math.round((screen.width/2)-(width/2));
		var top = Math.round((screen.height/2)-(height/2));
		FormWin = window.open(url, '', "width="+width+", height="+height+", menubar=no, resizable=no, scrollbars=no, status=no, border=no, toolbar=no, left="+left+", top="+top);
	}

/* Search */
Search = function () {	
	var data = '';
	data += 'searchSiteInner='  + jQuery('#searchSiteInner').val();
	data += '&search_site='  + jQuery('#search_site').val();
	data += '&search_group=' + jQuery('#search_group').val();

	jQuery('#searchButton').html('<img src="templates/common/images/ajax.gif" alt="loading..." />');
	
	Ajax.query ('search', '#searchResult', data, 'POST', true, function (block, response) {
	}, jQuery('#searchResult').html());
}	

/* Gallery */	
var Gallery = {
	  version : '0.0.1'
	  
	, exist : false
	
	, Init : function() {
		if(jQuery('#GalleryItemImage').size() > 0) { Gallery.exist = true;}
		if(Gallery.exist == true) { Gallery.GenItem(GalleryImagesList[0]);}
	} 
	
	, GenItem : function(item) {
		jQuery('#GalleryItemImage').html(Gallery.GetImageLarge(item));
		jQuery('#GalleryItemTitle').html(Gallery.GetImageTitle(item));
		jQuery('#GalleryItemDescription').html(Gallery.GetImageDescription(item));
		jQuery('#GalleryItemRoofing').html(Gallery.GetImageRoofing(item));
		jQuery('#GalleryItemDecoration').html(Gallery.GetImageDecoration(item));
	} 
	
	, GetImageLarge : function(item) {
		var sizeItem = (item.imageLargeSize).split('-');
		return '<a href="imageview/'+item.imageId+'" target="_blank"><img width="'+sizeItem[0]+'" height="'+sizeItem[1]+'" src="' + item.imageLarge + '" alt="' + item.imageTitle + '" /></a>'
	}
	, GetImageTitle : function(item) {
		return item.imageTitle;
	}
	, GetImageDescription : function(item) {
		return '<span>Разрешение: '+item.imageScreen+'</span>&nbsp;&nbsp;&nbsp;<span>Разрешение: '+item.imageSize+'</span>';
	}
	, GetImageRoofing : function(item) {
		return '<span>Кровля:</span> '+item.roofing;
	}
	, GetImageDecoration : function(item) {
		return '<span>Отделка:</span> '+item.decoration;
	}
	  
	, CarouselInitCallback : function(carousel) {
		jQuery('#GalleryCarouselNext').bind('click', function() {
	        carousel.next();
	        return false;
	    });
	
	    jQuery('#GalleryCarouselPrev').bind('click', function() {
	        carousel.prev();
	        return false;
	    });
	}

	, CarouselItemVisibleInCallback : function(carousel, item, i, state, evt) {
		var idx = carousel.index(i, GalleryImagesList.length);
        carousel.add(i, Gallery.getItemHTML(GalleryImagesList[idx - 1], idx-1 ));
	}

	, CarouselVisibleOutCallback : function(carousel, item, i, state, evt) {
		carousel.remove(i);
	}
	
	, getItemHTML : function(item, idx) {
		var sizeItem = (item.imageSmallSize).split('-');
		return '<a href="#" onclick="Gallery.GenItem(GalleryImagesList['+idx+']); return false;"><img src="' + item.imageSmall + '" width="'+sizeItem[0]+'" height="'+sizeItem[1]+'" alt="' + item.imageTitle + '" /></a>';
	}
}


/* 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..." />');

		Ajax.query (goHref, '#'+goBlock, '', 'POST', false, function (block, response) {
			Faq.InitLoadGroup();
			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;
		});  
	}

}

function showNewsesByCat (type, ob, url) 
	{
		ob.className = 'link-hovered';
		
		$('yearNews').innerHTML = waiting;
	
		ExecuteXMLCall(site_vdir+'plugins/news/listext'+url, 'newsblock', 'post', data,	true, '', $('newsblock').innerHTML);
	}

/* Menu */
var Menu = {

	  version	: '0.0.1'
	
	, menuTimeOut : 0
	, menuTimeOutMS : 200
	
	, Init : function() {
		jQuery('.menu-item').bind('mouseover', function() {
			jQuery('.menu-item').removeClass('menu-hovered');
			clearTimeout(Menu.menuTimeOut);
			jQuery('.submenu').filter('[id!='+this.id+'-submenu]').hide();
			if (jQuery('#' + this.id + '-submenu').css('display') == 'none') {
				jQuery('#' + this.id + '-submenu').fadeIn('fast');
			}
			jQuery('#' + this.id).addClass('menu-hovered');
		});
		jQuery('.menu-item').bind('mouseout', function() {
			Menu.menuTimeOut = setTimeout("jQuery('#" + this.id + "-submenu').fadeOut('fast'); jQuery('#" + this.id + "').removeClass('menu-hovered');", Menu.menuTimeOutMS);
		});
		jQuery('.submenu').bind('mouseout', function() {
			Menu.menuTimeOut = setTimeout("jQuery('#" + this.id + "').fadeOut('fast'); jQuery('#" + this.id.replace('-submenu','') + "').removeClass('menu-hovered');", Menu.menuTimeOutMS);
		});
		jQuery('.submenu').bind('mouseover', function() {
			clearTimeout(Menu.menuTimeOut);
		});
		jQuery('.inner-box').bind('mouseover', function() {
			clearTimeout(Menu.menuTimeOut);
		});
		jQuery('.submenu a').bind('mouseover', function() {
			clearTimeout(Menu.menuTimeOut);
		});

		return true;
	}
}


/* Faq */	
var Faq = {
	  version : '0.0.5'
	
	, preloader : '<img src="templates/common/images/ajax.gif" alt="loading..." />'
		
	, Init : function() {
		Faq.InitLoadGroup();
		Faq.InitShowToggle();
		Faq.InitSubmit();
	}

	, InitLoadGroup : function () {
		jQuery('.faqControlItem').bind('click', function() {
			var data = 'faqLoadGroup=true';
			jQuery('#faqControl').html(Faq.preloader);
			Ajax.query (this.href, '#faqblock', data, 'POST', false, function (block, response) {
				Faq.InitLoadGroup();
			}, jQuery('#faqblock').html());
			
			return false;
	    });
	}
	
	, InitSubmit : function() {
		jQuery('#faqFormContainer').submit(function(){return Faq.SubmitForm(jQuery("#faqFormContainer").attr("action"));});
	}

	, InitShowToggle : function() {
		jQuery('.faqFormShow').bind('click', function() {
			if(this.className == 'faqFormShow') {
				Faq.FormShow();
			} else {
				Faq.FormHide();
			}
			return false;
		});
		jQuery('.faqFormShow').show();
	}

	, FormShow : function() {
		//jQuery('.faqFormShow').html('<span>Скрыть</span>');
		jQuery('.faqFormShow').attr('class', 'faqFormHide');
		jQuery('#faqformcontent').show();
	}

	, FormHide : function() {
		//jQuery('.faqFormHide').html('<span>Задать вопрос</span>');
		jQuery('.faqFormHide').attr('class', 'faqFormShow');
		jQuery('#faqformcontent').hide();
	}

	, SubmitForm : function(action) {
		var faqData = Faq.CheckForm();
		if(faqData != false) {
			Ajax.query (action, '#faqform', faqData, 'POST', false, function (block, response) {
				Faq.InitShowToggle();
				Faq.InitSubmit();
				Faq.FormShow();
			}, jQuery('#faqform').html());
		}
		return false;
	}
	
	/* TODO: Заменить самописную функцию на валидатор форм на jQuery */
	, CheckForm : function() {
		var isValid = true;
		var dataCollection = 'faqDataSubmit=1';
		jQuery('#faqDataNameErr').html('&nbsp;');
		jQuery('#faqDataEmailErr').html('&nbsp;');
		jQuery('#faqDataQuestionErr').html('&nbsp;');
		jQuery('#faqDataImageErr').html('&nbsp;');
		
		var faqName = jQuery('#faqDataName').val();
		var faqEmail = jQuery('#faqDataEmail').val();
		var faqQuestion = jQuery('#faqDataQuestion').val();
		var faqImage = jQuery('#faqDataImage').val();

		if(faqName == '') {
			jQuery('#faqDataNameErr').html('заполните данное поле');
			isValid = false;
		} else {
			dataCollection += '&faqDataName='+faqName;
		}
		if(faqQuestion == '') {
			jQuery('#faqDataQuestionErr').html('заполните данное поле');
			isValid = false;
		} else {
			dataCollection += '&faqDataQuestion='+faqQuestion;
		}

		if(faqImage == '') {
			jQuery('#faqDataImageErr').html('введите код');
			isValid = false;
		} else {
			dataCollection += '&faqDataImage='+faqImage;
		}

		
		if(faqEmail == '') {
			jQuery('#faqDataEmailErr').html('заполните данное поле');
			isValid = false;
		} else {
			if(checkmail(faqEmail) == false) {
				jQuery('#faqDataEmailErr').html('некорректный email');
				isValid = false;
			} else {
				dataCollection += '&faqDataEmail='+faqEmail;
			}
		}


		return ((isValid == true) ? dataCollection : false);
	}
}


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