/* Document Load */
jQuery(document).ready(function() {
	Menu.Init();
	Cat.Init();
	Faq.Init();
	News.Init();
	setOpacity();
});

/* Common */

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

	/* Open window*/
		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);
		}
	
	/* 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) {
			jQuery('#pages').html('<img src="templates/common/images/ajax.gif" alt="loading..." />');

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

/* 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;
		}
	}
	
/* Cat */
	var Cat = {

		  version	: '0.0.1'
	
		, Init : function() {
			
			jQuery('div.catmenu').find('a.item').bind('click', function() {
				var id = jQuery(this).attr('id');
				if (jQuery('#'+id+'-block').size() == 0) return true;
				jQuery('div.catmenu').find('div.sub:visible').slideUp(300);
				jQuery('#'+id+'-block:hidden').slideToggle(300);
			return false;});
			
			jQuery('div.catmenu').find('div.sub:first').show();
			
		return true;}
	}

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

	}

/* 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('change', function() {
				var data = 'faqLoadGroup=true';
				jQuery('#faqControl').html(Faq.preloader);
				Ajax.query (this.value, '#faqblock', data, 'POST', false, function (block, response) {
					Faq.InitLoadGroup();
				}, jQuery('#faqblock').html());
				
				return false;
			});
		}
		
		, InitSubmit : function() {
			jQuery('#faqFormContainer').attr('onsubmit', 'return Faq.SubmitForm(jQuery("#faqFormContainer").attr("action"));');
		}

		, InitShowToggle : function() {
			jQuery('.faqFormShow').bind('click', function() {
				if(jQuery('#faqformcontent:visible').size() == 0) {
					Faq.FormShow();
					jQuery(this).find('img').attr('src','templates/default/images/buttons/answers.gif');
					jQuery('#faqAnswers').hide();
				} else {
					Faq.FormHide();
					jQuery(this).find('img').attr('src','templates/default/images/buttons/faq.gif');
					jQuery('#faqAnswers').show();
				}
				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();
			var faqPublic 	= jQuery('#faqDataPublic').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;
				}
			}

			dataCollection += '&faqDataPublic='+faqPublic;

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

/*  eshop scripts
 *  TODO: move to jQuery 
 */
 
 		
	function removeInvalidChars (input) {
		currentValue = Math.abs(Number(jQuery(input).val().replace(/[^\d]/g,"")));
		currentValue = (currentValue == 0) ? 1 : currentValue;
		jQuery(input).val((currentValue > 100000) ? 100000 : currentValue);
	}

    function AddBasketItem(id, link) {

		jQuery('#order-' + id + '-ajax').html('<img src="templates/common/images/ajax.gif" alt="..." />');

		jQuery.ajax({
		    cache		: false,
		    timeout		: 10000,
		    dataType	: 'html',
		    type		: 'POST',
		    
		    url			: jQuery(link).attr('href'),
		    data		: {'count':$('#count-'+id).attr("value"), 'selectedid':id, 'ajax':'true'},
		    
		    error: function(){
		    },
		    
		    success: function(response){
				
				jQuery('#order-' + id).html(response);	
				reloadMiniCart(jQuery(link).attr('href'));
		    }
	   	});

	return false;}
	
	function  reloadMiniCart (href) {
		jQuery.ajax({
		    cache		: false,
		    timeout		: 10000,
		    dataType	: 'html',
		    type		: 'POST',
		    
		    url			: 'minibasket',
		    data		: {'ajax':'true'},
		    
		    error: function(){
		    },
		    
		    success: function(response){
				jQuery('#minibasket').html(response);	
		    }
	   	});
	}
	
	MakePrice = function (price) {
	
		var temp = new Array();
		var globaltemp = new Array();
		var retPrice = new Array();
		var tempStr = new String(price);

		var retStr;
		var retStr2;

		globaltemp = tempStr.split('.');
		
		temp = globaltemp[0].split('');
		temp.reverse();

		for (var j=0; j< temp.length; j++)
		{
			retPrice.push(temp[j]);
			if ((j+1) % 3 == 0) 
			{
				retPrice.push('&nbsp;');
			}
		}
		
		retPrice.reverse();
		
		retStr = retPrice.join('');

		if (globaltemp[1])
		{
			retStr2 = '.'+globaltemp[1].substr(0,2);
		}
		else
		{
			retStr2 = '.00';
			
		}

		return retStr+retStr2;
	}
