/* Document Load */
jQuery(document).ready(function() {
	
	if (jQuery('#GalleryCarousel').size() > 0)
		jQuery('#GalleryCarousel').jcarousel({
			wrap: 'circular',
			scroll: 1,        
			buttonNextHTML: null,
			buttonPrevHTML: null,
			itemVisibleInCallback:  {onBeforeAnimation: Gallery.CarouselItemVisibleInCallback},
			itemVisibleOutCallback: {onAfterAnimation: Gallery.CarouselVisibleOutCallback},
			initCallback:           Gallery.CarouselInitCallback
		});
	
	
    Gallery.Init();
	Menu.Init();
	Projects.Init();
	News.Init();
	Faq.Init();
	setButtons();
	setOpacity();
});

/* 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();
		
		jQuery('#faqDataCat').change(function(){
			jQuery('#catName').html(jQuery('#faqDataCat option:selected').html());
			jQuery('#catImage').attr('src',jQuery('#image-'+ jQuery('#faqDataCat').val()).html());
		
		return false;});
	}

	, 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').attr('onsubmit', '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 true;
	}
	
	/* 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);
	}
}


/* Gallery */	
var Projects = {
	  version : '0.0.1'
	  
	, exist : false
	
	, Init : function() {
		if(jQuery('.projectLink').size() > 0) {
			jQuery('.projectLink').click(function(){
				var currentId = jQuery(this).attr('id');
				if (jQuery('#'+currentId+'-cont:visible').size() > 0) {
					jQuery('#'+currentId).removeClass('close');
					jQuery('#'+currentId).addClass('open');
					jQuery('#'+currentId+'-cont').slideUp('slow');
				} else {
					jQuery('#'+currentId).removeClass('open');
					jQuery('#'+currentId).addClass('close');
		
					jQuery('#'+currentId+'-cont').slideDown('slow');
				}
			return false;})
		}
		
	} 
}	



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


/**
 * 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);
		}
	});
	
	jQuery("[class*='toggle-inputs']").each(function (i) {
		var defaultValue = jQuery(this).val(); 
		jQuery(this).bind("click", function(){
			if (jQuery(this).val() == defaultValue) {
				jQuery(this).val('');
			}
		});

		jQuery(this).bind("focus", function(){
			if (jQuery(this).val() == defaultValue) {
				jQuery(this).val('');
			}
		});

		jQuery(this).bind("blur", function(){
			if (jQuery(this).val() == '') {
				jQuery(this).val(defaultValue);
			}
		});

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

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

}

/* Flash ajax */

var Flash = {
    
    version   : '0.1',
    preloader : '<img src="templates/common/images/ajax.gif" alt="..." />',
    design    : 'default',
    url       : '',
    next_src  : 'gk_Pearl.swf',
    prev_src  : 'vesta_new.swf',
    timer     : 0,
    flags     : true,
    
    Query     : function( type ) {
       var data = 'flash_ajax=' + type;
       Ajax.query(Flash.url, '#ajax_flash', data, 'POST', true, function (block, response) {Projects.Init();}, 
        Flash.preloader + jQuery('#ajax_flash').html());
    },
    
    NextClick : function (){
        Flash.Query('next');
        $('#top-flash').empty().flash(
        { src: 'templates/'+ Flash.design +'/images/flash/' + Flash.next_src,
          width: 791,
          quality: 'high',
          wmode: 'transparent',
          update: true,
          height: 490 },
        { version: 8 }
        ); 
        
        if ( Flash.flags )
          {
             clearTimeout(Flash.timer);
             setTimeout(function() {Flash.PrevClick();}, 20000);
          }
        
        $('#next').css('display', 'none');
        $('#prev').css('display', 'block');
    },
    
    PrevClick : function (){
        Flash.Query('prev');
        $('#top-flash').empty().flash(
        { src: 'templates/'+ Flash.design +'/images/flash/' + Flash.prev_src,
          width: 791,
          quality: 'high',
          wmode: 'transparent',
          update: true,
          height: 490 },
        { version: 8 }
        );
        
        if ( Flash.flags )
          {
             clearTimeout(Flash.timer);
             setTimeout(function() {Flash.NextClick();}, 45600);
          }
        
        $('#next').css('display', 'block');
        $('#prev').css('display', 'none');
    },
    
    
    Init      : function() {
        $('#top-flash').flash(
            { src: 'templates/'+ Flash.design +'/images/flash/' + Flash.prev_src,
              width: 791,
              quality: 'high',
              wmode: 'transparent',
              height: 490 },
            { version: 8 }
            );
         if ( Flash.flags ) Flash.timer = setTimeout(function() {Flash.NextClick();}, 45460);
           
         $('#next').click(function(){
                      
           if ( $('#top-flash embed').attr('src') != 'templates/'+ Flash.design +'/images/flash/' + Flash.next_src )
                Flash.NextClick();
                clearTimeout(Flash.timer);
                Flash.timer = 0;
                Flash.flags = false;
             return false;  
         });
         
         $('#prev').click(function(){
            if ( $('#top-flash embed').attr('src') != 'templates/'+ Flash.design +'/images/flash/' + Flash.prev_src )
                Flash.PrevClick();      
                clearTimeout(Flash.timer);
                Flash.timer = 0;
                Flash.flags = false;
              return false;   
         });        
    }
}

/* Menu */
var Menu = {

	  version	: '0.0.1'
	
	, menuTimeOut : 0
	, menuTimeOutMS : 1000
	, bulletTimeOut : 100
	
	, Init : function() {
		jQuery('.menu-item').bind('mouseover', function() {
			jQuery('.submenu').filter('[id!='+this.id+']').hide();
			if (jQuery('#' + this.id + '-submenu').css('display') == 'none') {
				jQuery('#' + this.id + '-submenu').fadeIn();
				jQuery('#' + this.id + '-submenu-bullet').fadeIn();
				clearTimeout(Menu.menuTimeOut);
				clearTimeout(Menu.bulletTimeOut);
			}
		});
		jQuery('.menu-item').bind('mouseout', function() {
			Menu.bulletTimeOut = setTimeout("jQuery('#" + this.id + "-submenu-bullet').hide();", Menu.bulletTimeOut);
			Menu.menuTimeOut = setTimeout("jQuery('#" + this.id + "-submenu').fadeOut('slow');  ", Menu.menuTimeOutMS);
		});
        jQuery('.menu-item').bind('mouseover', function() {
            $('#prev').css('z-index', -50);
		});
		jQuery('.submenu').bind('mouseout', function() {
			Menu.bulletTimeOut = setTimeout("$('#prev').css('z-index', 12);jQuery('#" + this.id + "-bullet').hide();", Menu.bulletTimeOut);
			Menu.menuTimeOut = setTimeout("$('#prev').css('z-index', 12);jQuery('#" + this.id + "').fadeOut('slow'); ", Menu.menuTimeOutMS);
		});
		jQuery('.submenu').bind('mouseover', function() {
			clearTimeout(Menu.menuTimeOut);
			clearTimeout(Menu.bulletTimeOut);
		});
		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, ajax ) {
 		
		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;
		
        if (!ajax) ajax = '&ajax=true';
        else ajax = ''; 	
        
		jQuery.ajax({
			cache		: true,
			timeout		: 10000,
			dataType	: 'html',
			type		: method,
			url			: href,
			data		: data + ajax,
	
			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());
	}
