/* Inits */
var searchText = "Поиск";
var lastIndex;

$(document).ready(function() {
	initSearch();
	initCarousel();
	initVerticalCarousel();
	initZoomFlags();
	initContentTable();
	wrapInputElements();
});

function setStylish() {
	$('.ui-datepicker-month, .ui-datepicker-year').sSelect( {ddMaxHeight: '256px'} );
}

function wrapInputElements() {
	$( '#news input[type=text]' ).wrap("<span class='typetext'></span>");
	$( '#news textarea' ).wrap("<span class='ts'><span class='lt'><span class='rt'><span class='lb'><span class='rb'></span></span></span></span></span>");
	$( '#news select' ).wrap("<span class='ls'><span class='rs'></span></span>");
	$( '#news ol li' ).each(function( index, elem ){
		$(this).html('<span>'+$( this ).html()+'</span>');
	});
	$('<input type="text" class="txt">').insertBefore( '#news select' ).focus( function(){
		$( this ).blur();
	} );
	$( '#news select' ).each( function(){
		$(this).prev('input').val( $.trim( $(this).find('option:selected').text() ) );
	} ).change( function(){
		$(this).prev('input').val( $.trim( $(this).find('option:selected').text() ) );
	} );
}

/* Functions */
function trace( str ) {
//	console.log( str );
}

/* Horizontal Carousel */
function initCarousel() {
	if( !$('#image-carousel').length ) return;

	var nStartSlide = getCookie('nImagePanelStartSlide');
	if (undefined == nStartSlide) {
	    nStartSlide = 0;
	}
	
	//alert( nStartSlide );

	var slider = $('#image-carousel').bxSlider({
		auto:false,
		infiniteLoop: true,
		controls: false,
		startingSlide: Number(nStartSlide),
		onBeforeSlide: function(currentSlide, totalSlides){
//		  $('.field-name-field-custom .field-item').append('<p class="check">Slide index ' + currentSlide + ' of ' + totalSlides + ' total slides has completed.');
			trace( currentSlide );
			$('#image-navigation a[rel]').removeClass('active');
			$('#image-navigation a[rel=' + currentSlide + ']').addClass('active');
		}
	});

	var textslider = $( '#text-carousel' ).bxSlider({
		auto:false,
		infiniteLoop: true,
		controls: false,
		startingSlide: Number(nStartSlide),
		autoControls: true
	});

	$( "#image-panel" ).mouseover( function(){
		slider.stopShow();
		textslider.stopShow();
	} );

	$( "#image-panel" ).mouseout( function(){
		slider.startShow();
		textslider.startShow();
	} );

	$('#image-navigation .left_arrow').click(function(){
		slider.goToPreviousSlide();
		textslider.goToPreviousSlide();
		return false;
	});

	$('#image-navigation .right_arrow').click(function(){
		slider.goToNextSlide();
		textslider.goToNextSlide();
		return false;
	});

	$('#image-navigation a[rel]').click(function(){
	   var thumbIndex = $('#image-navigation a[rel]').index(this);
		// call the "goToSlide" public function
		slider.goToSlide(thumbIndex);
		textslider.goToSlide(thumbIndex);

		// remove all active classes
		$('#image-navigation a[rel]').removeClass('active');
		// assign "pager-active" to clicked thumb
		$(this).addClass('active');
		// very important! you must kill the links default behavior
		return false;
	});

	// Choose slide to show on page load
	slider.goToSlide( nStartSlide );
	textslider.goToSlide( nStartSlide );

	if (++nStartSlide  >= slider.getSlideCount()) {
	    nStartSlide = 0;
	}

	setCookie('nImagePanelStartSlide', nStartSlide, 30*24*60*60);
}


/* Vertical Carousel */
function initVerticalCarousel() {
	if( !$('#list-projects').length ) return;

	var list_projects = $('#list-projects').bxSlider({
		auto:true,
		mode: 'vertical',
		infiniteLoop: true,
		controls: false,
		displaySlideQty: 3,
		moveSlideQty: 1,
		autoControls: false,
		onBeforeSlide: function(currentSlide, totalSlides){
			trace( currentSlide );
			$('#project-navigation a[rel]').removeClass('active');
			$('#project-navigation a[rel=' + currentSlide + ']').addClass('active');
		}
	});

	$( "#projects" ).mouseover( function(){
		list_projects.stopShow();
	} );

	$( "#projects" ).mouseout( function(){
		list_projects.startShow();
	} );

	$('#project-navigation .left_arrow').click(function(){
		list_projects.goToPreviousSlide();
		return false;
	});

	$('#project-navigation .right_arrow').click(function(){
		list_projects.goToNextSlide();
		return false;
	});

	$('#project-navigation a[rel]').click(function(){
	   var thumbProjectIndex = $('#project-navigation a[rel]').index(this);
		// call the "goToSlide" public function
		list_projects.goToSlide(thumbProjectIndex);

		// remove all active classes
		$('#project-navigation a[rel]').removeClass('active');
		// assisgn "pager-active" to clicked thumb
		$(this).addClass('active');
		// very important! you must kill the links default behavior
		return false;
	});
}


/* Search */
function initSearch() {
	var objSearchInput = $('#search input[type=text]');
	objSearchInput.val( searchText );

	objSearchInput.focus( function() {
			objSearchInput.val( "" );
		}
	);

	objSearchInput.blur( function() {
			if( objSearchInput.val() == '' ) {
				objSearchInput.val( searchText );
			}
		}
	);
}

/* Fancy PopUp */
function initFancyBox() {
	if( !$('#popup').length ) return;
//	$("a#popup").fancybox({
//		'opacity'		: true,
//		'overlayShow'	: true,
//		'transitionIn'	: 'elastic',
//		'transitionOut'	: 'elastic',
//		'width'		: 680,
//		'height'		: 495,
//		'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
//		'type'			: 'swf',
//		'swf'			: {
//			 'wmode'		: 'transparent',
//			'allowfullscreen'	: 'true'
//		}
//	});
	$("a#popup").click(function() {
		$.fancybox({
				'opacity'		: true,
				'overlayShow'	: true,
				'transitionIn'	: 'elastic',
				'transitionOut'	: 'elastic',
				'width'		: 680,
				'height'		: 495,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
					 'wmode'		: 'transparent',
					'allowfullscreen'	: 'true'
				}
			});

		return false;
	});
}

function initZoomFlags() {
	$('#countries li').hover(function(){
			$(this)
				.stop().animate({fontSize:"155%"}, 400)
				.find('p').stop().animate({top:"61px", left:"2px"}, 400).end()
				.find("img").stop().animate({width:"100px",height:"76px",left:"4px",top:"-24px"}, 400);
			var newsource = $(this).find('img').attr("src").replace('.png', '.jpg');
			$(this).find('img').attr("src", newsource );
		},
		function(){
			$(this)
				.stop().animate({fontSize:"100%"}, 400)
				.find('p').stop().animate({top:"55px", left:"1px"}, 400).end()
				.find("a img").stop().animate({width:"63px",height:"48px",left:"22px",top:"0"}, 400);
				var oldsource = $(this).find('img').attr("src").replace('.jpg','.png');
				$(this).find('img').attr("src", oldsource );
		});
}

function getMonthName(month) {
 var arr_months = ['Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря'];
 return arr_months[ parseInt(month - 1) ];
}

function format_date(str) { // формат даты должен быть ДД*ММ[*ГГ[ГГ]]
	var format_str, d_day, d_month, d_year = '';
	if(str == '') return('');
	d_day = (str.substring(0, 2))-0;
	d_month = (str.substring(3, 5))-0;
	if(str.length > 5) {
		d_year = str.substring(6, str.length);
	}
	if(d_day && d_month) {
		format_str = '<span class="day">' + d_day + '</span> <span class="month">' + getMonthName(d_month) + '</span> ' + d_year;
	} else {
		format_str = str;
	}
	return(format_str);
}

function initContentTable() {
	if( !$('#news table').length ) return;
	$('#news table tr:odd').addClass('odd');
}

//function initDatePicker() {
//	if( !$('#from').length && !$('#to').length ) return;
//	$(function(){
//	  $("#from").datepicker( {
//	   buttonImage: '../img/calendar/select_button.png',
//	   changeMonth: true,
//	   changeYear: true,
//	   beforeShow: function() {
//			setTimeout( setStylish, 10 );
//	   },
//	   onChangeMonthYear: function(year, month, inst) {
//			setTimeout( setStylish, 10 );
//	   }
//	  });
//	});
//
//	$(function(){
//	  $("#to").datepicker( {
//	   buttonImage: '../img/calendar/select_button.png',
//	   changeMonth: true,
//	   changeYear: true,
//	   beforeShow: function() {
//			setTimeout( setStylish, 10 );
//	   },
//	   onChangeMonthYear: function(year, month, inst) {
//			setTimeout( setStylish, 10 );
//	   }
//	  });
//	});
//}

// возвращает cookie если есть или undefined
function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
	"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	))
    return matches ? decodeURIComponent(matches[1]) : undefined 
}

// уcтанавливает cookie
function setCookie(name, value, props)
{
    props = props || {}
    var exp = props.expires

    if (typeof exp == "number" && exp)
    {
	var d = new Date()
	d.setTime(d.getTime() + exp*1000)
	exp = props.expires = d
    }
    
    if (exp && exp.toUTCString) { props.expires = exp.toUTCString() }
    value = encodeURIComponent(value)
    var updatedCookie = name + "=" + value
    
    for(var propName in props)
    {
	updatedCookie += "; " + propName
	var propValue = props[propName]
	if(propValue !== true){ updatedCookie += "=" + propValue }
    }
    
    document.cookie = updatedCookie
}

// удаляет cookie
function deleteCookie(name) {
    setCookie(name, null, { expires: -1 })
}

