/* Author: 
Nikolay Dyankov
*/

$(document).ready(function() {
	if (window.PIE) {
	    $('.box-with-shadow, .big-block-nav, .big-block-nav ul, .big-block-nav ul li, .big-block-nav ul li:first-child, #services-bg, #services-bg:before, #services-bg:after, #services-bg ul, body header nav ul li a, #header-content div h2, input, textarea, .news-image, .news-image img,#services-subnav > ul, th span ul li, .body-contacts #content ul li, .rab-vreme, .custom-select .select, .custom-select ul, .custom-select li, #timeline-bar, #timeline-inner section article .certificate span:after, #timeline-inner > article, #header-content p, #header-content h2,#header-content h2 span, body.body-news .custom-select, body.body-contacts #content, #header-wrap #lang span, #header-wrap #lang ul, .fieldset-submit').each(function() {
	        PIE.attach(this);
	    });
	}
	// flags
	var lang = false, popupActive = true, activeSelect = 0, dragSlider = false, ie = false, mouseX, mouseY, eMouseX, eMouseY, initX;
	// vars
	var viewportwidth, viewportheight;
	var articleWidth = $('#timeline section article').width();
	var articleSectionOffset;
	var sliderMin, sliderMax;
	var lastTimelineContentHeight = 0;
	var initHeight = true;
	var servicesActive = false;
	var servicesTimeout;
	
	// init
	getViewportDimentions();
	ie = (IsIE8Browser()) ? true : false;
	replaceImg();
	setupMainNav();
	setupCustomFileInputs();
	setupCustomSelects();
	setupTables();
	setClassesToPartnerBoxes();
	setupBigBlockNav();
	setupAccordeon();
	
	// init timeline
	if ($('body.body-about-us').length != 0) {
		fillYears();
		putCertificates();
	}
	
	// object event listeners
	// timeline
	$('#timeline .certificate').click(function(e) {
		moveSliderTo(e);
	});
	$('#timeline article header').click(function(e) {
		moveSliderTo(e);
	});
	$('#timeline-bar').click(function(e) {
		moveSliderTo(e);
	});
	$('#expand-timeline-button').click(function() {
		expandTimeline();
	});
	$('#close-timeline-button').click(function() {
		shrinkTimeline();
	});
	$('#services-subnav ul li').click(function() {
		expandAccordeon($(this).find('a'));
	});
	$('#pop-development').hover(function() {
		$('#services-subnav ul').hide();
	});
	$('#services').click(function() {
		servicesActive = true;
		$('#services-bg').fadeIn();
		$('#header-wrap > header > nav .active').removeClass('active');
		$(this).addClass('active');
	});
	$('#pop-outsourcing').hover(function(e) {
		$('#services-subnav ul').hide();
		$('#services-subnav ul#'+$(this).attr('id').replace('pop', 'sub')).show();
	});
	$('#pop-infrastructure').hover(function(e) {
		$('#services-subnav ul').hide();
		$('#services-subnav ul#'+$(this).attr('id').replace('pop', 'sub')).show();
	});
	$('#pop-consult').hover(function(e) {
		$('#services-subnav ul').hide();
		$('#services-subnav ul#'+$(this).attr('id').replace('pop', 'sub')).show();
	});
	$('#services-subnav ul').mouseout(function(e) {
		if ($(e.target).is('ul')) {
			$('#services-subnav ul').hide();
		}
	});
	$('.body-contacts #content ul li').click(function() {
		$(this).siblings('.selected').removeClass('selected');
		$(this).addClass('selected');
		
		$('.address').hide();
		var targetId = $(this).attr('id').replace('list', 'address');
		$('#'+targetId).fadeIn();
	});
	$('#apply').click(function() {
		$('#apply-form-wrap').fadeIn();
		if (window.PIE) {
		    $('input, textarea, .custom-select .select, .custom-select ul, .custom-select li, .fieldset-submit, #apply-form-wrap header,  #apply-form-wrap header h1, #apply-form-wrap, .popup-box').each(function() {
		        PIE.attach(this);
		    });
		}
	});
	$('#apply-form-wrap .close').click(function() {
		$('#apply-form-wrap').fadeOut(200);
	});
	$('input[type=file]').change(function() {
		$(this).siblings('input').val($(this).val());
	});
	$('.input-file-button').click(function() {
		$(this).siblings('input[type="file"]').trigger('click');
	});
	$('.file-input-wrap input[type="text"]').click(function() {
		$(this).siblings('input[type="file"]').trigger('click');
	});
//	$('.custom-select .select').click(function() {
//		if (activeSelect != 0 && activeSelect != $(this).closest('.custom-select').attr('id')) {
//			var selectToHide = $('.custom-select#'+activeSelect);
//			selectToHide.find('.options').hide();
//			activeSelect = 0;
//
//			selectToHide.css({ "z-index" : 50 });
//		}
//
//		if (activeSelect == $(this).closest('.custom-select').attr('id')) {
//			var selectToHide = $('.custom-select#'+activeSelect);
//			selectToHide.find('.options').hide();
//			activeSelect = 0;
//
//			selectToHide.css({ "z-index" : 50 });
//		} else {
//			$(this).siblings('.options').show();
//			activeSelect = $(this).closest('.custom-select').attr('id');
//
//			$('.custom-select'+activeSelect).css({ "z-index" : 51 });
//		}
//	});
//	$('.custom-select .options ul li').click(function() {
//		var selectToHide = $('.custom-select#'+activeSelect);
//		selectToHide.find('.options').hide();
//		activeSelect = 0;
//
//		selectToHide.css({ "z-index" : 50 });
//
//		$('select#'+$(this).closest('.custom-select').attr('id')).find('option').removeAttr('selected');
//		$('select#'+$(this).closest('.custom-select').attr('id')).find('option[name='+$(this).attr('id')+']').attr('selected', 'selected');
//		$(this).closest('.custom-select').find('.selected').removeClass('selected');
//		$(this).closest('.custom-select').find('.select').html($(this).html());
//		$(this).addClass('selected');
//	});

	//custom selects
	$('.custom-select .select').click(function() {
		var target = $(this);
		if (activeSelect != 0 && activeSelect != $(this).closest('.custom-select').attr('id')) {
			var selectToHide = $('.custom-select#'+activeSelect);
			selectToHide.find('.options').hide();
			activeSelect = 0;
			
			selectToHide.css({ "z-index" : 50 });
		}
		
		if (activeSelect == $(this).closest('.custom-select').attr('id')) {
			var selectToHide = $('.custom-select#'+activeSelect);
			selectToHide.find('.options').hide();
			activeSelect = 0;
			
			selectToHide.css({ "z-index" : 50 });
		} else {
			$(this).siblings('.options').show();
			activeSelect = $(this).closest('.custom-select').attr('id');
			$('.custom-select#'+activeSelect).css({ "z-index" : 99999 });
		}
	});
	$('.custom-select .options ul li').click(function() {
		var selectToHide = $('.custom-select#'+activeSelect);
		selectToHide.find('.options').hide();
		activeSelect = 0;
		
		selectToHide.css({ "z-index" : 50 });
		
		$('select#'+$(this).closest('.custom-select').attr('id')).find('option').removeAttr('selected');
		$('select#'+$(this).closest('.custom-select').attr('id')).find('option[value='+$(this).attr('id')+']').attr('selected', 'selected');
		$(this).closest('.custom-select').find('.selected').removeClass('selected');
		var target = $(this);

		$(this).closest('.custom-select').find('.select').html(target.html());
		$(this).addClass('selected');
		
		if ($(this).closest('.custom-select').attr('id') == 'news-archive-select') {
			$('#archive-form').submit();
		}

	});
	
	$('#careers-table th').click(function() {
		var button = $(this).find('.button');
		if (button.hasClass('up')) {
			button.removeClass('up').addClass('down');
		} else {
			button.removeClass('down').addClass('up');
		}
	});
	$('.partners-popup-close').click(function() {
		closePopup();
	});
	$('.logo-box span').click(function() {
		showPopupFor($(this).closest('.logo-box'));
	});
	$('.logo-box img').click(function() {
		showPopupFor($(this).closest('.logo-box'));
	});
	$('.big-block-nav ul li').mousedown(function() {
		$(this).addClass('click');
	});
	$('.big-block-nav ul li').mouseup(function() {
		$(this).removeClass('click');
	});
	$('#lang').click(function(e) {
		if (!lang) {
			lang = true;
		} else {
			lang = false;
		}
		$(this).find('ul').toggle();
		if ($(e.target).is('a')) {
			$(this).find('span').html($(e.target).html());
		}
	});
	$('#featured li a').hover(function() {
		ourFeaturesBounce($(this).closest('li'));
	});
	$('.accordeon > li').click(function(e) {
		console.log($(this), $(e.target));
		if ($(e.target).closest('header').length != 0 || $(e.target).is('header')) {
			$(this).find('section').slideToggle();
			$(this).toggleClass('active');
		}
	});
	
	// document event listeners
	$(document).click(function(e) {
		if (servicesActive && $(e.target).closest('#services').length == 0) {
			servicesActive = false;
			$('#services-bg').hide();
			$('#services-subnav ul').hide();

			
			if ($('body').attr('class').search(' ') === -1) {
				$('#header-wrap > header > nav .active').removeClass('active');
				$('#'+$('body').attr('class').replace('body-', '')).addClass('active');
			}
		}
		if (activeSelect != 0 && !$(e.target).hasClass('select') && !$(e.target).is('li')) {
			var selectToHide = $('.custom-select#'+activeSelect);
			selectToHide.find('.options').hide();
			activeSelect = 0;

			// manage z-index
			selectToHide.css({ "z-index" : 999 });
			selectToHide.siblings('.options').css({ "z-index" : 998 });
		}
		
		if (lang && $(e.target).closest('#lang').length == 0 && $(e.target).attr('id') !== 'lang') {
			$('#lang ul').hide();
			lang = false;
		}
		if (popupActive && $(e.target).closest('.partners-popup').length == 0 && $(e.target).closest('.logo-box').length == 0) {
			closePopup();
		}
		if ($('.body-careers').length != 0 && 
			$('#careers-table .visible').length != 0 &&
			($(e.target).closest('th').find('.visible').length == 0 || $(e.target).find('.visible').length == 0)) {
			$('#careers-table .visible').removeClass('visible').fadeOut(150);
		}
	});
	$(document).mousedown(function(e) {
		if ($(e.target).is('span') && $(e.target).closest('#timeline-bar').length != 0 && !dragSlider) {
			e.preventDefault();
			prepareSliderForDrag(e);
		}
	});
	$(document).mousemove(function(e) {
		if (dragSlider) {
			fDragSlider(e);			
		}
	});
	$(document).mouseup(function(e) {
		if (dragSlider) {
			finishDragging(e);
		}
	});
	
	// timeline functions
	function activateYear() {
		var yearNum = 1 + Math.round(($('#timeline-bar-slider').position().left - articleSectionOffset) / articleWidth);
		var target = $('#timeline section article').first();
		for (var i=0; i<yearNum; i++) {
			target = target.next();
		}
		$('#timeline .selected').removeClass('selected');
		target.addClass('selected');
		
		$('#timeline-inner > article span').css({ "left" : yearNum*articleWidth + 16 });
		
		$('#timeline-inner > article p').html(target.find('p').html());
		$('#timeline-inner > article header').html(target.find('header').html());
		$('#timeline-content').animate({ "height" : getTimelineContentHeight(false) }, 200, function() {
			$('#timeline-inner > article').fadeIn(200);
		});
	}
	function finishDragging(e) {
		dragSlider = false;
		$('#timeline-bar-slider').animate({ "left" : minMax(articleSectionOffset + Math.round($('#timeline-bar-slider').position().left/articleWidth)*articleWidth, sliderMin, sliderMax) }, 200, function() {
			activateYear();
		});
		$('#timeline-bar span').animate({ "left" : minMax(articleSectionOffset + Math.round($('#timeline-bar-slider').position().left/articleWidth)*articleWidth, sliderMin, sliderMax) }, 200);	
	}
	function moveSliderTo(e) {
		if (!$(e.target).is('span')) {
			var left = minMax(articleSectionOffset + Math.round((e.pageX - $('#timeline-bar').offset().left - 70)/articleWidth)*articleWidth, sliderMin, sliderMax);
			$('#timeline-bar-slider').animate({ "left" : left });
			$('#timeline-bar span').animate({ "left" : left }, function() {
				activateYear();
			});
		}
	}
	function fDragSlider(e) {
		mouseX = e.pageX;
		$('#timeline-bar-slider').css({ "left" : minMax(initX - (eMouseX - mouseX), sliderMin, sliderMax) });
		$('#timeline-bar span').css({ "left" : minMax(initX - (eMouseX - mouseX), sliderMin, sliderMax) });
	}
	function prepareSliderForDrag(e) {
		initX = $('#timeline-bar-slider').position().left;
		eMouseX = e.pageX;
		dragSlider = true;
	}
	function shrinkTimeline() {
		if (!ie) {
			$('#timeline-inner').fadeOut(200, function() {
				$('#close-timeline-button').fadeOut(300);
				$('body > header').animate({ "margin-bottom" : 230 }, 300).css({ "overflow" : 'visible' });
				$('#timeline-content').animate({ "height" : 0 }, 300).css({ "overflow" : 'visible' });
				$('#stripe-top').animate({ "height" : 16 }, 300).css({ "overflow" : 'visible' });
				$('#stripe-bottom').animate({ "height" : 28 }, 300).css({ "overflow" : 'visible' });
				$('#expand-timeline-button').fadeIn(500);	
			});
		} else {
			$('#timeline-inner').hide();
			$('#close-timeline-button').hide();
			$('body > header').animate({ "margin-bottom" : 230 }, 300).css({ "overflow" : 'visible' });
			$('#timeline-content').animate({ "height" : 0 }, 300).css({ "overflow" : 'visible' });
			$('#stripe-top').animate({ "height" : 16 }, 300).css({ "overflow" : 'visible' });
			$('#stripe-bottom').animate({ "height" : 28 }, 300).css({ "overflow" : 'visible' });
			$('#expand-timeline-button').show();
		}
	}
	function expandTimeline() {
		if (!ie) {
			$('#expand-timeline-button').fadeOut(300);
		} else {
			$('#expand-timeline-button').hide();
		}
		$('body > header').animate({ "margin-bottom" : 30 }, 300).css({ "overflow" : 'visible' });
		$('#timeline-content').animate({ "height" : getTimelineContentHeight(true) }, 300, function() {
			if (!ie) {
				$('#timeline-inner').fadeIn(200);
			} else {
				$('#timeline-inner').show();
			}
			setupTimelineVars();
		});
		$('#stripe-top').animate({ "height" : 84 }, 300).css({ "overflow" : 'visible' });
		$('#stripe-bottom').animate({ "height" : 114 }, 300).css({ "overflow" : 'visible' });
		if (!ie) {
			$('#close-timeline-button').fadeIn(500);
		} else {
			$('#close-timeline-button').show();		
		}
	}
	function setupTimelineVars() {
		articleSectionOffset = $('#timeline section').position().left;
		sliderMin = -37;
		sliderMax = $('#timeline article').last().position().left - 37;
	}
	function minMax(val, min, max) {
		var result;
		result = (val < min) ? min : val;
		result = (val > max) ? max : result;
		return result;
	}
	function putCertificates() {
		$('#timeline article').each(function() {
			if ($(this).hasClass('certificate')) {

			}
		});
	}
	function fillYears() {
		var lastYear = $('#timeline article').last().find('header').html();
		var articleCount = 0;
		
		$('#timeline section article').each(function() {
			articleCount = articleCount + 1;
		});
		
		console.log(articleCount);
		
		lastYear = parseInt(lastYear) + parseInt(1);
		
		while (articleCount < 21) {
			$('#timeline section').append('<div class="fill-year"><div class="fill-year-header">'+lastYear+'</div></div>');
			articleCount = parseInt(articleCount) + parseInt(1);
			lastYear = parseInt(lastYear) + parseInt(1);
		}
		
//		lastYear++;
//		
//		console.log(lastYear);
//		for (var i = lastYear; i <= 2015; i++) {
//			console.log('add: '+i);
//			$('#timeline section').append('<div class="fill-year"><div class="fill-year-header">'+i+'</div></div>');
//		}
	}
	function getTimelineContentHeight(old) {
		if (initHeight) {
			initHeight = false;
			lastTimelineContentHeight = 212;
		} else if (!old) {
			lastTimelineContentHeight = 212 + $('#timeline-inner > article').outerHeight();
		}
		return lastTimelineContentHeight;
	}
	
	// functions
	function getViewportDimentions() {
		// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

		 if (typeof window.innerWidth != 'undefined')
		 {
		      viewportwidth = window.innerWidth;
		      viewportheight = window.innerHeight;
		 }

		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

		 else if (typeof document.documentElement != 'undefined'
		     && typeof document.documentElement.clientWidth !=
		     'undefined' && document.documentElement.clientWidth != 0)
		 {
		       viewportwidth = document.documentElement.clientWidth;
		       viewportheight = document.documentElement.clientHeight;
		 }

		 // older versions of IE

		 else
		 {
		       viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
		 }
	}
	function replaceImg() {
		$('img').each(function() {
			var src = $(this).attr('src');
			var alt = $(this).attr('alt');
		});
	}
	function expandAccordeon(target) {
		var name = target.attr('href').slice(target.attr('href').search('#')+1);
		console.log(name);
		$('.accordeon').find('a[name='+name+']').closest('li').addClass('active').find('section').slideDown();
	}
	function setupAccordeon() {
		var accordeon = $('.accordeon');
		if (accordeon.length != 0) {
			var name = document.URL.slice(document.URL.search('#')+1);
			var link = 0;

			if (document.URL.search('#') != -1) {
				link = accordeon.find('a[name='+name+']');
			}	

			if (link.length != 0 && link.length != undefined) {
				link.closest('li').addClass('active').find('section').slideToggle();
			} else if (name == 'about-us') {
//				accordeon.find('li').first().addClass('active').find('section').slideToggle();
			}
		}
	}
	function setupMainNav() {
		var i = $('body').attr('class').search(' ');
		if (i == -1) {
			$('#header-wrap > header nav ul li#'+$('body').attr('class').replace('body-', '')).addClass('active');
		} else {
			$('#header-wrap > header nav ul li#'+$('body').attr('class').substr(0, i).replace('body-', '')).addClass('active');
		}
		
		if ($('body.body-index').length != 0) {
			$('#header-wrap > header nav .active').removeClass('active');
		}
		
		// services
		var counter;
		$('#services-subnav ul').each(function() {
			counter = 0;
			$(this).find('li').each(function() {
				$(this).addClass('li-'+counter);
				counter = counter + 1;
			})
		});
	}
	function setupCustomFileInputs() {
		$('input[type=file]').each(function() {
			$(this).wrap('<div class="file-input-wrap"></div>');
			$(this).after('<input type="text">').after('<div class="input-file-button">Избери</div>');
		});
	}
	function setupCustomSelects() {
		$('select').each(function() {
			if ($(this).length != 0) {
				var id = $(this).attr('id');
				var selected = $(this).find('option[selected]');
				var html = '';
				html += '<div class="custom-select" id="'+$(this).attr('id')+'">';
				html += '	<div class="arrow"></div>';
				html += '	<div class="select">Избери опция:</div>';
				html += '	<div class="options">';
				html += '		<ul>';
	
				$(this).find('option').each(function() {
					html += '<li id="'+$(this).attr('value')+'"><a>'+$(this).html()+'</a></li>';
				});
				html += '		</ul>';
				html += '	</div>';
				html += '</div>';
		
				$(this).before(html).hide();
		
				var last = 0;
				$('.custom-select#'+id).find('li').each(function() {	last = $(this);		});
				last.addClass('last');
				
				if (selected.length != 0) {
					// if there was a selected option, select it again
					$('.custom-select#'+id+' .select').html(selected.html());
					$('.custom-select#'+id+' li#'+selected.attr('value')).addClass('selected');
				} else {
					$('.custom-select#'+id+' .select').html($(this).find('option').first().html());
				}
			}
		});
		
		if (window.PIE) {
		    $('.custom-select .select, .custom-select ul, .custom-select li').each(function() {
		        PIE.attach(this);
		    });
		}
	}
	function setupTables() {
		$('table').each(function() {
			$('tr').each(function() {
				$('td').each(function() {
					if (!$(this).next().is('td')) {
						$(this).addClass('last-in-row');
					}
				});
				$('th').each(function() {
					if (!$(this).next().is('th')) {
						$(this).addClass('last-in-row');
					}
				});
			});
		});
	}
	function setupBigBlockNav() {
		if ($('.big-block-nav').length != 0) {
			var counter=0, flag=0;
			$('.big-block-nav ul li').each(function() {
				if ($(this).hasClass('active')) {
					flag = 1;
				}
				if (!flag) { counter = counter + 1; }
			});

			$('.big-block-nav .arrow').css({ "left" : 75 + counter*195 });
			if ($('.big-block-nav .active').length == 0) {
				$('.big-block-nav .arrow').hide();
			}
		}
	}
	function setClassesToPartnerBoxes() {
		if ($('body').hasClass('body-partners') || $('body').hasClass('body-clients')) {
			var counter = 1;
			var partners = new Array();
			var path = ($('body').hasClass('body-clients')) ? 'clients' : 'partners';
			
			$('#content').find('.logo-box').each(function() {
				var id=$(this).attr('id');
				$(this).append('<img src="http://www.lirex.bg/data/uploads/filemanager/'+path+'/'+id+'_ef.jpg">');	
				$(this).hover(function() {
					$(this).find('img').attr('src', 'http://www.lirex.bg/data/uploads/filemanager/'+path+'/'+id+'.jpg');
	
				}, function() {
					$(this).find('img').attr('src', 'http://www.lirex.bg/data/uploads/filemanager/'+path+'/'+id+'_ef.jpg');
				});
	
				if (counter % 5 == 0) {
					$(this).addClass('last-row');
				}
				counter = counter + 1;
				partners[counter] = $(this);
	
				if ($(this).next().is('h2')) {
					for(var i=counter; i>counter-5; i--) {
						partners[i].addClass('last-column');
					}
				}
			});
			
			for(var i=counter; i>counter-5; i--) {
				partners[i].addClass('last-column');
			}
		}
	}
	function closePopup() {
		$('.partners-popup').fadeOut();
		popupActive = false;
	}
	function showPopupFor(box) {
		popupActive = true;
		var popup = $('.partners-popup');
		var content = box.find('.partner-content').html();
		var link = box.find('a').attr('href');
		
		popup.fadeIn(100);
		popup.find('.partners-popup-content').html(content);
		if (link > 0) {
			popup.find('a').attr('href', link);
		} else {
			popup.find('.partners-popup-visit').css('display','none')
		}
		
		popup.css({ "left" : box.offset().left - 40, "top" : box.offset().top + 140 })/*.css({ "height" : popup.find('.partners-popup-content').height()-95 })*/;
		
		console.log(popup.offset().top, popup.outerHeight(), $('footer').offset().top, $('footer').outerHeight());
		
		if (popup.offset().top + popup.outerHeight() > $('footer').offset().top + $('footer').outerHeight()) {
			popup.css({ "top" : box.offset().top - popup.outerHeight() - 10 });
			popup.removeClass('arrow-top').addClass('arrow-bottom');
		} else {
			popup.removeClass('arrow-bottom').addClass('arrow-top');
		}
	}
	function ourFeaturesBounce(li) {
		var icon = li.find('.icon');
		var shadow = li.find('.shadow');

		icon.animate({ "top" : 50 }, 200, function() {
			icon.animate({ "top" : 60 }, 500);
		});

		shadow.animate({ "width" : 15, "left" : 89 }, 200, function() {
			shadow.animate({ "width" : 40, "left" : 77 }, 500);
		});
	}
	function IsIE8Browser() {
	    var rv = -1;
	    var ua = navigator.userAgent;
	    var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
	    if (re.exec(ua) != null) {
	        rv = parseFloat(RegExp.$1);
	    }
	    return (rv == 4);
	}
});

