hs.graphicsDir = '/images/highslide/graphics/';
hs.align = 'center';
hs.transitions = ['expand', 'crossfade'];
hs.fadeInOut = true;
hs.dimmingOpacity = 0.8;
hs.outlineType = 'rounded-white';
hs.captionEval = 'this.a.title'; //this.thumb.alt, this.thumb.title, this.a.title //Given the captionEval option is set to 'this.img.alt', the caption is grabbed from the alt attribute of the thumbnail image.
hs.marginBottom = 105; // make room for the thumbstrip and the controls
hs.numberPosition = 'caption';
hs.blockRightClick = true;
hs.showCredits = false;
//hs.lang.number = '%1 / %2';
//hs.lang.loadingText = 'Зарежда се...';

// lang = BG;
if( js_lang == 'bg' ) {
	hs.lang = {
		cssDirection: 'ltr',
		loadingText : 'Зарежда се...',
		loadingTitle : 'Кликнете за да се откажете',
		focusTitle : 'Кликнете за да прегледате',
		fullExpandTitle : 'Покажи в актуална големина (клавиш F)',
		previousText : 'Предишен',
		previousTitle : 'Предишен (стрелка наляво)',
		nextText : 'Следващ', 
		nextTitle : 'Следващ (стрелка надясно)',
		moveText : 'Премести',
		moveTitle : 'Премести',
		closeText : 'Затвори', 
		closeTitle : 'Затвори (клавиш ESC)', 
		resizeTitle : 'Оразмери',
		playText : 'Слайдшоу',
		playTitle : 'Стартирай слайдшоу (клавиш Spacebar)',
		pauseText : 'Пауза',
		pauseTitle : 'Пауза на слайдшоу (клавиш Spacebar)',
		fullExpandText : '1:1',
		number: 'Снимка %1 от %2',
		restoreTitle : 'Кликнете за да затворите картинката, кликнете и местете мишката за да преместите. Използвайте стрелките за предишен и следващ.'
	};
}

// Add the slideshow providing the controlbar and the thumbstrip
hs.addSlideshow({
	//slideshowGroup: 'group1',
	interval: 5000,
	repeat: false,
	useControls: true,
	overlayOptions: {
		className: 'text-controls',
		position: 'bottom center',
		relativeTo: 'viewport',
		offsetY: -60
	},
	thumbstrip: {
		position: 'bottom center',
		mode: 'horizontal',
		relativeTo: 'viewport'
	}
});
/*
// no big image! and no trigger click!
	$('.content_gallery_view .itemImage a').bind('click', function(event){
		event.preventDefault();
		$('.content_gallery_view .imagesList a:eq(0)').trigger('click');
	});
*/

jQuery(document).ready(function($){
	
	calculte_nav_offset(); // call this before lavaLamp (if present)
	
	buttonOverState('.newsletterCommon .divSubmitButton .submitButton', 'submitButtonOver');
	buttonOverState('.leftMenu_1 li > a:not(".selected")', 'selected');
	buttonOverState('.leftMenu_2 li > a:not(".selected")', 'selected');
	buttonOverState('.formApplication_JS .divSubmit .inputSubmit', 'inputSubmitOver'); // IE6 only needs this
	
	// Set captcha by JS
	$("input[name='cap_prot']").val('1');
	
	$('.nav_main_ul').superfish({
		dropShadows: true
	});
	
	equalize_row_titles('.blockBellCenters .row', '.item .itemTitle');
	equalize_row_titles('.blockIzpitnaPodgotovka .row', '.item .itemTitle');
	equalize_row_titles('.content_style_courses .courses_home_cols', '.col_item .box_11_top_middle, .col_item .box_12_top_middle, .col_item .box_13_top_middle');
	
	runFlashHeader();
	runAdsHomeBanner_1(); // ads_home_banner_1
	
	$('.newsletterCommon .divInputText_232x21_blue_back .inputText, .blockNewsletterHome .divInputText .inputText').each(function(){
		$(this).watermark( $(this).val(), {'useNative': false} );
	});
	
	equalize_row_table_cells('.tableContentOneRow table, td .cc_middle', 'td .cc_middle');
	equalize_row_table_cells_vertical_align_top_2('.tableContentOneRowVerticalAlignTop table tr', 'td .cc_middle');
	//equalize_row_table_cells_vertical_align_top_2('.tableContent_7 table .row_first_last', 'td .cc_middle');
	//equalize_row_table_cells_vertical_align_top_2('.tableContent_7 table .row_inner', 'td .cc_middle');
	equalize_row_table_cells_vertical_align_top_2('.tableContent_7 table tr', 'td .cc_middle'); // call equalize function just once per row!
	
	
	collapseTableSpecificRows('.tableDetailsJobs .tableContent_7 > table'); // we can skip this and replace it using css - display: none; + different first time generation (Check that "equalize_row_table_cells_vertical_align_top_2()" works OK)
	collapseTableSpecificRows('.tableDetailsCambridgeIelts .tableContent_7 > table'); // we can skip this and replace it using css - display: none; + different first time generation (Check that "equalize_row_table_cells_vertical_align_top_2()" works OK)
	
	bindTableToggleNextRowEvent('.tableDetailsJobs .tableContent_7 .icon_quick_info');
	bindTableToggleNextRowEvent('.tableDetailsCambridgeIelts .tableContent_7 .icon_quick_info_2');
	
	
	$('#datepicker_course_start').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'dd/mm/yy',
		inline: false,
		//showOn: 'button', // default if not set - focus
		//showOn: 'both',
		buttonImage: '/images/common/icons/icon_date.jpg',
		buttonImageOnly: true // to show without a button tag
	});
	// Custom trigger event
	$("#datepicker_course_start_date_trigger").bind('click', function(){
		//$('#datepicker_course_start_date').focus(); // also works, but better use "datepicker('show')" method.
		$('#datepicker_course_start').datepicker('show');
	});
	
	
	// Contact form:
	$('#contact_subject_styled_select').styledSelect({
		"selectClass": "styledSelect_190_20"
		,"zIndexApply": true
		,"zIndexStart": 305 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 25 // 2011-04-01 - limit on closed state!
	});
	
	$('#filter_course_type').styledSelect({
		"selectClass": "styledSelect_159_20"
		,"zIndexApply": true
		,"zIndexStart": 305 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 22 // 2011-01-07 - limit on closed state!
	});
	$('#filter_start_date').styledSelect({
		"selectClass": "styledSelect_109_20"
		,"zIndexApply": true
		,"zIndexStart": 305 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#filter_course_time').styledSelect({
		"selectClass": "styledSelect_159_20"
		,"zIndexApply": true
		,"zIndexStart": 305 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 22 // 2011-01-07 - limit on closed state!
	});
	$('#filter_branch').styledSelect({
		"selectClass": "styledSelect_159_20"
		,"zIndexApply": true
		,"zIndexStart": 305 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 22 // 2011-01-07 - limit on closed state!
	});
	
	$('#form_qualification_degree').styledSelect({
		"selectClass": "styledSelect_305_20"
		,"zIndexApply": true
		,"zIndexStart": 305 // define greater z-index for top selects and decrease for the next (bottom)
	});
	
	
	$('#form_select_age').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 320 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_want_to_study_in').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 319 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_course_month_start').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 318 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_course_duration').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 317 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_course_type').styledSelect({
		"selectClass": "styledSelect_304_20"
		,"zIndexApply": true
		,"zIndexStart": 315 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_course_type_2').styledSelect({
		"selectClass": "styledSelect_304_20"
		,"zIndexApply": true
		,"zIndexStart": 315 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_your_level').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 314 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_accomodation_where').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 312 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_include_food').styledSelect({
		"selectClass": "styledSelect_215_20"
		,"zIndexApply": true
		,"zIndexStart": 311 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_select_transfer_to_airport').styledSelect({
		"selectClass": "styledSelect_304_20"
		,"zIndexApply": true
		,"zIndexStart": 310 // define greater z-index for top selects and decrease for the next (bottom)
	});
	
	// Application form
	$('#form_birthday_day').styledSelect({
		"selectClass": "styledSelect_60_20"
		,"zIndexApply": true
		,"zIndexStart": 320 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_birthday_month').styledSelect({
		"selectClass": "styledSelect_104_20"
		,"zIndexApply": true
		,"zIndexStart": 320 // define greater z-index for top selects and decrease for the next (bottom)
	});
	$('#form_birthday_year').styledSelect({
		"selectClass": "styledSelect_75_20"
		,"zIndexApply": true
		,"zIndexStart": 320 // define greater z-index for top selects and decrease for the next (bottom)
	});
	
	// added 2011-06-10
	$('#form_kinship_relationships').styledSelect({
		"selectClass": "styledSelect_104_20"
		,"zIndexApply": true
		,"zIndexStart": 319 // define greater z-index for top selects and decrease for the next (bottom)
	});
	
	$('#form_student_class').styledSelect({
		"selectClass": "styledSelect_60_20"
		,"zIndexApply": true
		,"zIndexStart": 318 // define greater z-index for top selects and decrease for the next (bottom)
	});
	
	$('#form_certificate_name').styledSelect({
		"selectClass": "styledSelect_386_20"
		,"zIndexApply": true
		,"zIndexStart": 317 // define greater z-index for top selects and decrease for the next (bottom)
	});
	form_certificate_result_styled_select(); // use as function
	certificate_result_check_entered_result_event(); // bind onchange event
	certificate_result_check_entered_result(); // check on load
	// z-index: 317 for the form_certificate_result
	
	$('#course_alternative_1').styledSelect({
		"selectClass": "styledSelect_386_20"
		,"zIndexApply": true
		,"zIndexStart": 315 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 45 // 2011-04-01 - limit on closed state!
	});
	$('#course_alternative_2').styledSelect({
		"selectClass": "styledSelect_386_20"
		,"zIndexApply": true
		,"zIndexStart": 314 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 45 // 2011-04-01 - limit on closed state!
	});
	$('#course_alternative_3').styledSelect({
		"selectClass": "styledSelect_386_20"
		,"zIndexApply": true
		,"zIndexStart": 313 // define greater z-index for top selects and decrease for the next (bottom)
		,"closedOptionLimitChars": 45 // 2011-04-01 - limit on closed state!
	});
	$('#form_cannot_visit_day').styledSelect({
		"selectClass": "styledSelect_140_20"
		,"zIndexApply": true
		,"zIndexStart": 312 // define greater z-index for top selects and decrease for the next (bottom)
	});
	
	
	
	
	
	
	// Teaser
	$('#teaser_sequence_1').cycle({
		fx:     'scrollUp',
		speed:  1000,
	    timeout: 15000,
		pager:  '#nav_sequence_1',
		activePagerClass: 'selected',
		cleartypeNoBg: true, // ie6/7
		pause: 1,
		pagerAnchorBuilder: function(idx, slide) {
			// return selector string for existing anchor
			//return '#nav_sequence_1 li:eq(' + idx + ') a';
			
			//var temp = '#nav_sequence_1 div:eq(' + idx + ')';
			//alert(temp);
			
			return '#nav_sequence_1 a:eq(' + idx + ')';
	    }
	});
	
	// Here an option - stop this cycle! after displaying selected slide
	$("#nav_sequence_1 a").click(function (event) {
		event.preventDefault();
		$('#teaser_sequence_1').cycle('pause');
		/*
		// Resume sliding after NN miliseconds - timer
		var sequence_1_temp = function(){
			$("#teaser_sequence_1").cycle('resume');
		};
		setTimeout(sequence_1_temp, 10000);
		*/
    });
    
    
    // Here an another option - stop sliding on HOVER on the buttons!
	$("#nav_sequence_1 a").hover(
		function () {
			$("#teaser_sequence_1").cycle('pause');
		}, 
		function () {
			$("#teaser_sequence_1").cycle('resume');
		}
	);
	
	calculte_teaser_nav_offset();
	
	
	calculateWidgetSuitableSaveSpacePosition();
	calculateWidgetCourseFeatures2SaveSpacePosition();
	
	
	// Teaser 2 - partners rotation + pause on Over!
	$('.widgetPartnersTeaser .teaserContainer').cycle({
		fx:     'scrollUp',
		speed:  1000,
	    timeout: 4000,
		//pager:  '#nav_sequence_1',
		//activePagerClass: 'selected',
		cleartypeNoBg: true, // ie6/7
		pause: 1
		/*
		,pagerAnchorBuilder: function(idx, slide) {
			// return selector string for existing anchor
			//return '#nav_sequence_1 li:eq(' + idx + ') a';
			
			//var temp = '#nav_sequence_1 div:eq(' + idx + ')';
			//alert(temp);
			
			return '#nav_sequence_1 a:eq(' + idx + ')';
	    }
	    */
	});
	
	calendarAjax('now');
	
	$('#faqList').accordion({header: '.head',alwaysOpen: false, autoheight: false ,active: false});
	
	
	var contactOk=$("#cotactOk").html();
	if (contactOk != '' && contactOk != null){
	   return create({modal: true}, contactOk, 'Благодарим Ви!');
	}
	
	var message_error=$("#message_error").html();
	if (message_error != '' && message_error != null){
	   return create({modal: true}, message_error, 'Грешка');
	}
	
	$("#form_select_age").change(function(){
	   ukOfferRequestSelectOptions();
	});
	
	
	$(".icon_send_to_friend").fancybox({
		/*
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		*/
		'autoScale'			: true,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'onClosed'          : function(){
								actionEmailFriendFormOnClosed();
							  }
		//,'type'				: 'iframe'
	});
	
	// added 2011-04-01 - to improove user interaction
	$(".linkTerms").each(function(){
		var this_href = $(this).attr('href');
		
		var this_new_href = this_href.replace('/pg/', '/pgc/');
		//alert(this_new_href);
		
		$(this).attr('href', this_new_href);
		
		$(this).fancybox({
			'padding'			: 0,
			'overlayOpacity'	: 0.7,
			'overlayColor'		: '#000000',
			//'width'				: '75%',
			//'height'			: '75%',
			//'width'				: '760', // not working, but it is the default setting!?
			//'height'			: '340', // not working, but it is the default setting!?
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'onClosed'          : function(){
									
								  }
			,'type'				: 'iframe' // prevents messing the CSS
		});
	});
	
	/*
	$("#email_a_friend_submit").bind("click", function(){
		// use inline function
	});
	*/
	
	
	
	$("#form_accommodation_1").click(function(){
	    $("#Show_when_is_yes").show();
	});
	
	$("#form_accommodation_0").click(function(){
	    $("#Show_when_is_yes").hide();
	});
	
	///// Form application
	// invoice - toggle firm data fields
	applicationFormToggleInvoiceFirmData( $('.formApplication_JS input[name="invoice_type_firm"]') );
	$('.formApplication_JS input[name="invoice_type_firm"]').bind('change', function(){
		applicationFormToggleInvoiceFirmData(this);
	});
	
	updateInvoiceUsedName(); // call on load if errors occured...
	$('.formApplication_JS input[name="first_name_cyr"], .formApplication_JS input[name="second_name_cyr"], .formApplication_JS input[name="last_name_cyr"]').bind('change blur', function(){
		updateInvoiceUsedName();
	});
	
	$('#form_certificate_name').bind('change', function(){
		updateCertificateResultSelectContainer();
	});
	
	checkForOnlineTestResult(); // call on load to check for result and display an warning if necessary
	$('#checkForOnlineTestResult').bind('click', function(e){
		e.preventDefault();
		checkForOnlineTestResult();
	});
	
	
	/* // 2011-03-15 - after processing...
	$('#courseApplicationGenerateInvoice').bind('click', function(e){
		e.preventDefault();
		
		applicationInvoiceGenerate();
	});
	*/
	
	
});

//boxy message
function create(options, custom_text, custom_title) {
  options = $.extend({title: custom_title}, options || {});
  var dialog = new Boxy('<div style="min-width: 300px; min-height: 73px;"><p>'+custom_text+'</p></div>', options);
  return false;
}

function ukOfferRequestSelectOptions(){
    $("#form_select_age option:selected").each(function(){
        //alert($(this).attr('id'));
        if ($(this).attr('id') == 'form_select_age_option_1' || $(this).attr('id') == 'form_select_age_option_2'){
            $("#course_type_div_row").css('display', 'none');
            $("#course_type_div_row_2").css('display', 'none');
        } else if ($(this).attr('id') == 'form_select_age_option_3'){
            
            $("#course_type_div_row_2").css('display', 'block');
            $("#course_type_div_row").css('display', 'none');
            $("#form_select_course_type_2").css('display', 'none');
            /*$('#form_select_course_type_2').styledSelect({
        		"selectClass": "styledSelect_304_20"
        		,"zIndexApply": true
        		,"zIndexStart": 315 // define greater z-index for top selects and decrease for the next (bottom)
        	});*/
            
        } else {
            $("#course_type_div_row_2").css('display', 'none');
            $("#course_type_div_row").css('display', 'block');
            $("#form_select_course_type_2_option_0").attr('selected', 'selected');
        }
        
    });
}


function calendarAjax(date){
    rootCourseId=$("#rootCourseIdCalnedar").val();
    
    $.post('/ajax_calendar', { "rootId" : rootCourseId, "date" : date}, function (data, textStatus) {
        //alert(data);
		if (data != ''){
		    $(".widgetCalendar").html('');
		    $(".widgetCalendar").html(data);
		    rebindCalendarButtons();
		    /*
		    $('#ajax_table').remove();
		    $('#table_ajax_div').html(data);
		    equalize_row_table_cells_vertical_align_top_2('#ajax_table tr', 'td .cc_middle');
		    bindTableToggleNextRowEvent('#ajax_table .icon_quick_info_2');
		    */
		}
	});
}

function rebindCalendarButtons(){
    $("#calendarNextButton").unbind('click');
    $("#calendarPrevButton").unbind('click');
    
    $("#calendarNextButton").click(function(){
        calendarAjax('next');
        return false;
    });
    
    $("#calendarPrevButton").click(function(){
        calendarAjax('prev');
        return false;
    });
}

function calculte_nav_offset()
{
	var max_width = $('.nav_main').width();
	var nav_width = $('.nav_main > ul').width();
	//alert(max_width);
	//alert(nav_width);
	if(max_width>nav_width) {
		var margin_offset = (max_width-nav_width) / 2;
		if( margin_offset >0 ) {
			margin_offset = Math.floor(margin_offset);
			//alert(margin_offset);
			//$('#nav').width(nav_width).css('margin-left', margin_offset + 8); // we have 15px left offset of the background image in header. Use half of this width
			//$('#nav').css('margin-left', margin_offset + 8);
			$('.nav_main > ul').css('margin-left', margin_offset); // no correction needed
		}
	}
}

function calculte_teaser_nav_offset()
{
	var max_width = $('.nav_sequence_teaser').width();
	var nav_width = $('#nav_sequence_1').width();
	//alert(max_width);
	//alert(nav_width);
	if(max_width>nav_width) {
		var margin_offset = (max_width-nav_width) / 2;
		if( margin_offset >0 ) {
			margin_offset = Math.floor(margin_offset);
			//alert(margin_offset);
			//$('#nav').width(nav_width).css('margin-left', margin_offset + 8); // we have 15px left offset of the background image in header. Use half of this width
			//$('#nav').css('margin-left', margin_offset + 8);
			$('#nav_sequence_1').css('margin-left', margin_offset); // no correction needed
		}
	}
}


/* OnOver - add class for IE - Should be used on elements different from Links */
function buttonOverState(selector, className)
{
	/* Hover over the login button */
	$(selector).hover(function(){
		$(this).addClass(className);
	},
	function(){
		$(this).removeClass(className);
	});
}

/*
function carousel_001_initCallback(carousel)
{
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
	    carousel.startAuto(0);
	});
	
	carousel.buttonPrev.bind('click', function() {
	    carousel.startAuto(0);
	});
	
	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
	    carousel.stopAuto();
	}, function() {
	    carousel.startAuto();
	});
};
*/

function equalize_row_titles(selector_row, selector_title)
{
	$(selector_row).each(function(){
		// itemTitle
		var highest = 0;
		$(selector_title, this).each(function() {
			//alert( $(this).height() );
			var elem_height = $(this).height();
			if(elem_height>highest) {
				highest = elem_height;
			}
		});
		$(selector_title, this).height(highest); // use min-height except ie6
	});
}


function equalize_row_table_cells(selector_row, selector_title)
{
	$(selector_row).each(function(){
		// itemTitle
		var highest = 0;
		$(selector_title, this).each(function() {
			//alert( $(this).height() );
			var elem_height = $(this).height();
			if(elem_height>highest) {
				highest = elem_height;
			}
		});
		
		// FIX - when the highest = 29, 1 px difference ! Now all element will set height!
			//alert(highest); // 29
			//alert(elem_height); //14
			//alert(temp_differ); //15
			//alert(temp_differ_half); //7
		if(Math.floor(highest/2)!=Math.round(highest/2)) {
			highest = highest + 1; // convert to even
		}
		// END FIX
		
		count = 0;
		$(selector_title, this).each(function() {
			count++;
			
			//alert( $(this).height() );
			var elem_height = $(this).height();
			
			if(elem_height<highest) {
				temp_differ = Math.floor(highest-elem_height); // Math.floor(x) - rounded downwards to the nearest integer
				temp_differ_half = Math.floor(temp_differ/2);
				/*
				if(count==4) {
					alert(highest); // 29
					alert(elem_height); //14
					alert(temp_differ); //15
					alert(temp_differ_half); //7
				}
				*/
				$(this).height(highest-temp_differ_half).css('padding-top', temp_differ_half).css( 'padding-bottom', 0);
				//$(this).height(highest); // vertical-align: middle should be preserved!
			}
		});
	});
}


function equalize_row_table_cells_vertical_align_top(selector_row, selector_title)
{
	$(selector_row).each(function(){
		// itemTitle
		var highest = 0;
		$(selector_title, this).each(function() {
			//alert( $(this).height() );
			var elem_height = $(this).height();
			if(elem_height>highest) {
				highest = elem_height;
			}
		});
		
		// FIX - when the highest = 29, 1 px difference ! Now all element will set height!
			//alert(highest); // 29
			//alert(elem_height); //14
			//alert(temp_differ); //15
			//alert(temp_differ_half); //7
		if(Math.floor(highest/2)!=Math.round(highest/2)) {
			highest = highest + 1; // convert to even
		}
		// END FIX
		
		count = 0;
		$(selector_title, this).each(function() {
			count++;
			
			//alert( $(this).height() );
			var elem_height = $(this).height();
			
			if(elem_height<highest) {
				temp_differ = Math.floor(highest-elem_height); // Math.floor(x) - rounded downwards to the nearest integer
				temp_differ_half = Math.floor(temp_differ/2);
				/*
				if(count==4) {
					alert(highest); // 29
					alert(elem_height); //14
					alert(temp_differ); //15
					alert(temp_differ_half); //7
				}
				*/
				//
				
				if(count==5) {
					$(this).height(highest-temp_differ_half).css('padding-top', temp_differ_half).css( 'padding-bottom', 0);
				}
				else {
					$(this).height(highest); // vertical-align: middle should be preserved!?
				}
				
			}
		});
	});
}

function equalize_row_table_cells_vertical_align_top_2(selector_row, selector_elem_to_equalize)
{
	
	$(selector_row).each(function(){
		// itemTitle
		//console.log(this);
		
		var highest = 0;
		$(selector_elem_to_equalize, this).each(function() {
			//alert( $(this).height() );
			var elem_height = $(this).height();
			if(elem_height>highest) {
				highest = elem_height;
			}
		});
		
		// FIX (set highest to be even number!) - when the highest = 29, 1 px difference ! Now all element will set height!
			//alert(highest); // 29
			//alert(elem_height); //14
			//alert(temp_differ); //15
			//alert(temp_differ_half); //7
		if(Math.floor(highest/2)!=Math.round(highest/2)) {
			highest = highest + 1; // convert odd number to even
		}
		// END FIX
		
		count = 0; // may be no need of this, but leave it for debug...
		$(selector_elem_to_equalize, this).each(function() {
			count++;
			
			//alert( $(this).height() );
			var elem_height = $(this).height();
			
			if(elem_height<highest) {
				temp_differ = Math.floor(highest-elem_height); // Math.floor(x) - rounded downwards to the nearest integer
				temp_differ_half = Math.floor(temp_differ/2);
				/*
				if(count==4) {
					alert(highest); // 29
					alert(elem_height); //14
					alert(temp_differ); //15
					alert(temp_differ_half); //7
				}
				*/
				//
				
				if( $(this).hasClass('cc_vertical_middle') ) {
					$(this).height(highest-temp_differ_half).css('padding-top', temp_differ_half).css( 'padding-bottom', 0); // vertical-align: middle should be preserved!?
				}
				else {
					$(this).height(highest);
				}
				
			}
		});
	});
}

function bindTableToggleNextRowEvent(selector_table_row_icon)
{
	$(selector_table_row_icon).bind('click', function(event){
		event.preventDefault();
		//alert('clicked info button');
		// select current row, then select next (if present), then toggle (if current animation - stop and toggle?)?
		tableToggleNextRow(this);
	});
}

function collapseTableSpecificRows(selector_table)
{
	$(selector_table).each(function(){
		//alert(1);
		//console.log(this);
		// select all rows ".row_inner", then check if the next row is ".row_full_inner" and exists, then hide this ".row_full_inner"
		
		$(".row_inner", this).each(function(){
			
			//return false;
			
			// Check next row
			if( $(this).next().hasClass('row_full_inner') ) {
				if( $(this).next().hasClass('row_full_last') ) {
					// make this row last
					if( $(this).hasClass('row_first') ) {
						$(this).removeClass('row_first').addClass('row_first_last');
					}
					else { // if( $(this).hasClass('row_inner') )
						$(this).addClass('row_last');
					}
				}
				$(this).next().hide();
				//$(this).next().addClass('row_hidden');
			}
			
		});
		
	});
}

function tableToggleNextRow(this_link)
{
	// select current row, then select next (if present), then toggle (if current animation - stop and toggle?)?
	
	//var this_row = $(this_link).parents().filter(".row_inner"); // find("tr.row_inner") selects all rows!
	//var this_row = $(this_link).parents(".row_inner:eq(0)");
	var this_row = $(this_link).parents(".row_inner");
	
	//console.log(this_row);
	
	// Check next row
	
	//console.log( $(this_row).next() );return;
	
	if( $(this_row).next().hasClass('row_full_inner') ) {
		
		//console.log( $(this_row).next() );
		
		
		if( $(this_row).next().is(":hidden") ) { /* ie8 have problems with it using jquery 1.3.2, 1.4.4 fixes that */
		//if( $(this_row).next().hasClass("row_hidden") ) {
			if( $(this_row).hasClass('row_first_last') ) { // last - 1st case
				// make this row last
				$(this_row).removeClass('row_first_last').addClass('row_first');
				$(this_row).next().addClass('row_full_last');
			}
			else if( $(this_row).hasClass('row_last') ) { // last - 2nd case
				// make this row last
				$(this_row).removeClass('row_last');
				$(this_row).next().addClass('row_full_last');
			}
			else {
				//do not change classes!
			}
			$(this_row).next().show();
			//$(this_row).next().removeClass("row_hidden");
		}
		else {
			// display: block; -> switch to hidden
			if( $(this_row).next().hasClass('row_full_last') ) {
				// make this row last
				if( $(this_row).hasClass('row_first') ) {
					$(this_row).removeClass('row_first').addClass('row_first_last');
				}
				else { // if( $(this).hasClass('row_inner') )
					$(this_row).addClass('row_last');
				}
			}
			$(this_row).next().hide();
			//$(this_row).next().addClass("row_hidden");
		}
	}
	
}

ascOrDescUk=2;
ascOrDescAdults=2;
function coursesTableAjaxOrder(table_type, orderby, post, courseID){
    //alert(table_type);
    switch(table_type){
        case '3':
            //alert('ss');
            url='/ajax_table_uk';
            if (ascOrDescUk == 1){
                ascOrDescUk=2;
                ascOrDesc='desc';
            } else {
                ascOrDescUk=1;
                ascOrDesc='asc';
            }
            //alert('2');
            
        break;
        
        case '2':
            url='/ajax_table_adults';
            if (ascOrDescAdults == 1){
                ascOrDescAdults=2;
                ascOrDesc='desc';
            } else {
                ascOrDescAdults=1;
                ascOrDesc='asc';
            }
        break;
        
        case '4':
            url='/ajax_table_work';
            if (ascOrDescAdults == 1){
                ascOrDescAdults=2;
                ascOrDesc='desc';
            } else {
                ascOrDescAdults=1;
                ascOrDesc='asc';
            }
        break;
        
        case '1':
            url='/ajax_table_students';
            if (ascOrDescAdults == 1){
                ascOrDescAdults=2;
                ascOrDesc='desc';
            } else {
                ascOrDescAdults=1;
                ascOrDesc='asc';
            }
        break;
    }
    
    //alert(url);
    
    $.post(url, { "orderby" : orderby, "post" : post, "order": ascOrDesc, "courseID": courseID}, function (data, textStatus) {
        //alert(data);
		if (data != ''){
		    $('#ajax_table').remove();
		    $('#table_ajax_div').html(data);
		    equalize_row_table_cells_vertical_align_top_2('#ajax_table tr', 'td .cc_middle');
		    bindTableToggleNextRowEvent('#ajax_table .icon_quick_info_2');
		    
		}
	});
	
	return false;
}


function runFlashHeader()
{
	var flashvars = {};
	var params = {
		wmode:"transparent"
	};
	var attributes = {};
	
	if( js_lang == 'bg' ) {
		var filename = '/flash/avobell-header-bg.swf';
	} else {
		var filename = '/flash/avobell-header-en.swf';
	}
	
	swfobject.embedSWF( filename , "id_flash_header", "709", "220", "9.0.0","/js/expressInstall.swf", flashvars, params, attributes);
}

function runAdsHomeBanner_1()   // ads_home_banner_1
{
	var flashvars = {};
	var params = {
		wmode:"transparent"
	};
	var attributes = {};
	
	//console.log(ads_home_banner_1);
	if( typeof ads_home_banner_1 == "object" ) { // the object is empty on all inner pages. This breaks the rest of JS if not checked!
		$.each( ads_home_banner_1, function(index, value){
			//console.log(this);
			//console.log(this.div_id);
			swfobject.embedSWF( this.file_name , this.div_id , this.file_width , this.file_height , "9.0.0", "/js/expressInstall.swf", flashvars, params, attributes); // IE6/7 throws an error, but works OK
		});
	}
	return;
}



function calculateWidgetSuitableSaveSpacePosition()
{
	var box_height = $('.widgetSuitableCourses .box_9_middle').height();
	var preserve_space_height = $('.widgetSuitableCourses .savePlaceForEggIcon').height();
	var preserve_space_margin_top = box_height - preserve_space_height;
	
	//console.log(box_height);
	//console.log(preserve_space_height);
	//console.log(preserve_space_margin_top);
	
	if( preserve_space_margin_top<0 ) {
		preserve_space_margin_top = 0;
	}
	
	$('.widgetSuitableCourses .savePlaceForEggIcon_1').height(preserve_space_margin_top);
}

function calculateWidgetCourseFeatures2SaveSpacePosition()
{
	var box_height = $('.widgetCourseFeatures_2 .box_8_top_middle').height();
	var preserve_space_height = $('.widgetCourseFeatures_2 .savePlaceForEggIcon').height();
	var preserve_space_margin_top = box_height - preserve_space_height;
	
	//console.log(box_height);
	//console.log(preserve_space_height);
	//console.log(preserve_space_margin_top);
	
	if( preserve_space_margin_top<0 ) {
		preserve_space_margin_top = 0;
	}
	
	$('.widgetCourseFeatures_2 .savePlaceForEggIcon_1').height(preserve_space_margin_top);
}

function openNewWindow(URL, window_name, features) {
	new_window = window.open(URL, window_name, features);
	new_window.focus();
}


function submitEmailFriendForm( selectedAction, form_classname, test_value_1 )
{
	//selectedAction='send_email_to_friend', form_classname = '.email_a_friend_form', test_value_1 = 0
	if( selectedAction==undefined) {
		selectedAction = 'send_email_to_friend';
	}
	if( form_classname==undefined) {
		form_classname = '.email_a_friend_form';
	}
	if( test_value_1==undefined) {
		test_value_1 = 0;
	}
	
	// Get Language
	//var ajax_lang = $("#ajax_lang").val();
	var ajax_lang = $("input[name='ajax_lang']", form_classname).val();
	
	// Get Variables
	var var_cap_prot = $("input[name='cap_prot']", form_classname).val();
	var var_email = $("input[name='email']", form_classname).val();
	var var_course_id = $("input[name='course_id']", form_classname).val();
	
	//console.log(ajax_lang);
	//console.log(var_email);
	
	$.post(
		"/email-a-friend-clean"
		,{
			"action": selectedAction
			,"cap_prot": var_cap_prot
			,"email": var_email
			,"course_id": var_course_id
			,"test_value_1": test_value_1
			,"lang": ajax_lang
		}
		,function(responseText, textStatus, XMLHttpRequest) {
			// Callback function!!!   	//alert("done");
			//console.log(responseText);      //alert(textStatus); // success
			
			$(responseText).each(function(key, serverData) {
				//alert("a");
				if(serverData.result==1) {
					//alert("success");
					//console.log(serverData);
					if(serverData.position=="alert") {
						//myAlert(serverData.data);
						alert(serverData.data);
					}
					if(serverData.position=="update_form_text") {
						//myAlert(serverData.data);
						$("#email_a_friend .email_a_friend_messages").html(serverData.data);
					}
					if(serverData.position=="update_clear_form_values") {
						//myAlert(serverData.data);
						$("#email_a_friend input[name='email']").val('');
					}
					if(serverData.position=="update_datepicker_bind") {
						//setTimeout("assignOfferDatePickers()", 900);
					}
				}
			});
			
		}
		,"json"
	);
	
}

function actionEmailFriendFormOnClosed()
{
	$("#email_a_friend .email_a_friend_messages").html('');
	$("#email_a_friend input[name='email']").val('');
}


function applicationFormToggleInvoiceFirmData(this_elem)
{
	if( $(this_elem).is(":checked") ) {
		//var this_value = 1;
		$('#invoice_type_firm_fields').show();
	} else {
		//var this_value = 0;
		$('#invoice_type_firm_fields').hide();
	}
	//alert(this_value);
}


function applicationInvoiceGenerate()
{
	
	var invoice_data = applicationInvoiceDataCheck();
	
	if( invoice_data === false ) {
		return false;
	}
	
	$.ajax({
		type: 'POST'
		,url: '/ajax-course-application-invoice.php'
		//,data: { id: 'id_1' }
		,data: invoice_data
		,dataType: 'json'
		,success: function(dataResponse){
			//console.log(dataResponse);
			$.each( dataResponse, function(indexInArray, this_value){
				if( this_value.result == 1 ) { // we have valid responce
					if( this_value.action == 'open_new_window' ) {
						window.open(this_value.data,"vn_bel_print","menubar=1,resizable=1,width=705,height=460");
					}
				}
			});
		}
	});
	
}


function applicationInvoiceDataCheck()
{
	var invoice_type_firm = 0;
	if( $('.formApplication_JS input[name="invoice_type_firm"]').is(":checked") ) {
		invoice_type_firm = 1;
	}
	//alert(invoice_type_firm);
	
	var errors = '';
	
	// Also get the course_id (to get the type), and the table_record_id to generate Price...
	var course_id = $('.formApplication_JS input[name="course_id"]').val();
	var course_record_id = $('.formApplication_JS input[name="course_record_id"]').val();
	
	
	if( invoice_type_firm==1 ) {
		
		// check for firm data
		var firm_name = $('.formApplication_JS input[name="firm_name"]').val();
		var firm_dds_number = $('.formApplication_JS input[name="firm_dds_number"]').val();
		var firm_address = $('.formApplication_JS input[name="firm_address"]').val();
		var firm_mol = $('.formApplication_JS input[name="firm_mol"]').val();
		//alert(firm_name);
		
		if( errors == '' && firm_name == '' ) {
			errors = 'Не сте посочили име на фирма. Полето е задължително, защото сте избрали издаване на фактура на фирма.';
		}
		/*
		if( errors == '' && firm_dds_number == '' ) {
			errors = 'Не сте посочили ДДС номер на фирма.';
		}
		if( errors == '' && firm_address == '' ) {
			errors = 'Не сте посочили данъчен адрес на фирма.';
		}
		if( errors == '' && firm_mol == '' ) {
			errors = 'Не сте посочили МОЛ на фирма.';
		}
		*/
		
		if( errors == '' ) {
			var result = {
							'firm_name': firm_name
							//,'firm_dds_number': firm_dds_number
							//,'firm_address': firm_address
							//,'firm_mol': firm_mol
							,'course_id': course_id
							,'course_record_id': course_record_id
			};
			return result;
		} else {
			alert(errors); // display with style?
			return false;
		}
		
	}
	else {
		
		// check for private data
		var first_name_cyr = $('.formApplication_JS input[name="first_name_cyr"]').val();
		var second_name_cyr = $('.formApplication_JS input[name="second_name_cyr"]').val();
		var last_name_cyr = $('.formApplication_JS input[name="last_name_cyr"]').val();
		//var birthday_day = $('.formApplication_JS select[name="birthday_day"]').val();
		//var birthday_month = $('.formApplication_JS select[name="birthday_month"]').val();
		//var birthday_year = $('.formApplication_JS select[name="birthday_year"]').val();
		//alert(first_name_cyr);
		
		if( errors == '' && first_name_cyr == '' ) {
			errors = 'Празно поле за име на кирилица.';
		}
		if( errors == '' && second_name_cyr == '' ) {
			errors = 'Празно поле за презиме на кирилица.';
		}
		if( errors == '' && last_name_cyr == '' ) {
			errors = 'Празно поле за фамилия на кирилица.';
		}
		
		if( errors == '' ) {
			var result = {
							'first_name_cyr': first_name_cyr
							,'second_name_cyr': second_name_cyr
							,'last_name_cyr': last_name_cyr
							//,'birthday_day': birthday_day
							//,'birthday_month': birthday_month
							//,'birthday_year': birthday_year
							//,'address': address
							,'course_id': course_id
							,'course_record_id': course_record_id
			};
			return result;
		} else {
			alert(errors); // display with style?
			return false;
		}
		
	}
	
	
	return {};
}


function updateInvoiceUsedName()
{
	if( $('#invoice_note').is('*') ) { // use only for form, not the archive!
		var first_name_cyr = $('.formApplication_JS input[name="first_name_cyr"]').val();
		var second_name_cyr = $('.formApplication_JS input[name="second_name_cyr"]').val();
		var last_name_cyr = $('.formApplication_JS input[name="last_name_cyr"]').val();
		
		if( first_name_cyr!='' && second_name_cyr!='' && last_name_cyr!='' ) {
			$('#invoice_note').html('Фактурата за направеното плащане ще бъде издадена на името на: <b>'+first_name_cyr+' '+second_name_cyr+' '+last_name_cyr+'</b>.<br />Можете да изберете издаване на фактура на фирма:');
		}
	}
}

function form_certificate_result_styled_select()
{
	$('#form_certificate_result').styledSelect({
		"selectClass": "styledSelect_386_20"
		,"zIndexApply": true
		,"zIndexStart": 316 // define greater z-index for top selects and decrease for the next (bottom)
	});
}


function updateCertificateResultSelectContainer()
{
	var cert_id = $('#form_certificate_name').val();
	//alert(cert_id);
	if( cert_id>0 ) {
		// check for available results for this certificate
		$.ajax({
			type: 'POST'
			,url: '/ajax-course-application-get-certificate-results.php'
			//,data: { id: 'id_1' }
			,data: { 'cert_id': cert_id }
			,dataType: 'json'
			,success: function(dataResponse){
				//console.log(dataResponse);
				$.each( dataResponse, function(indexInArray, this_value){
					if( this_value.result == 1 ) { // we have valid responce
						if( this_value.action == 'alert' ) {
							alert(this_value.data);
						}
						else if( this_value.action == 'update_cert_results' ) {
							//alert(this_value.data);
							if( this_value.data != '' ) {
								$('#certificate_result_container').html(this_value.data);
								form_certificate_result_styled_select();
								certificate_result_check_entered_result_event(); // rebind onchange event
							}
						}
					}
				});
			}
		});
		
		// rebuild the certificate_result select + rebind events
	}
	
}

function certificate_result_check_entered_result_event()
{
	$('#form_certificate_result').bind('change', function(){
		certificate_result_check_entered_result();
	});
}

function certificate_result_check_entered_result()
{
	//$('#form_certificate_result').bind('change', function(){
		
		// we need to:
		// - select the chosen course_id, course_record_id, certificate_id and certificate_result_id
		// check via AJAX for enough result. If not enough - display a message (warning box?)
		var course_id = $('.formApplication_JS input[name="course_id"]').val();
		var course_record_id = $('.formApplication_JS input[name="course_record_id"]').val();
		var cert_id = $('#form_certificate_name').val();
		var cert_result_id = $('#form_certificate_result').val();
		
		if( course_id>0 && course_record_id>0 && cert_id>0 && cert_result_id>0 ) {
			// check for available results for this certificate
			$.ajax({
				type: 'POST'
				,url: '/ajax-course-application-check-certificate-results.php'
				//,data: { id: 'id_1' }
				,data: {
					'course_id': course_id,
					'course_record_id': course_record_id,
					'cert_id': cert_id,
					'cert_result_id': cert_result_id
				}
				,dataType: 'json'
				,success: function(dataResponse){
					//console.log(dataResponse);
					$.each( dataResponse, function(indexInArray, this_value){
						if( this_value.result == 1 ) { // we have valid responce
							if( this_value.action == 'alert' ) {
								alert(this_value.data);
							}
							else if( this_value.action == 'cert_result_warning_show' ) {
								//alert(this_value.data);
								if( this_value.data == 1 ) {
									$('#certificate_warning').show();
								}
							}
							else if( this_value.action == 'cert_result_warning_hide' ) {
								//alert(this_value.data);
								if( this_value.data == 1 ) {
									$('#certificate_warning').hide();
								}
							}
						}
					});
				}
			});
			
			// rebuild the certificate_result select + rebind events
		}
		
	//});
}

function checkForOnlineTestResult()
{
	//$('#checkForOnlineTestResult').bind('click', function(){
		
		// Check if it is archive or not - 2011-03-31
		if( $("#div_online_test_result").is('*') ) {
			// OK
		}
		else {
			// stop the ajax call
			return;
		}
		
		var fingerprint = $('.formApplication_JS input[name="fingerprint"]').val();
		
		if( fingerprint!='' ) {
			// check for available results for this certificate
			
			$('#div_online_test_result b').html('&nbsp;&nbsp;&nbsp;<img src="/images/ajax-loader-2.gif" alt="Моля, почакайте..." />');
			
			$.ajax({
				type: 'POST'
				,url: '/ajax-course-application-check-online-test-result.php'
				//,data: { 'id': 'id_1' }
				,data: {
					'fingerprint': fingerprint
				}
				,dataType: 'json'
				,success: function(dataResponse){
					//console.log(dataResponse);
					$.each( dataResponse, function(indexInArray, this_value){
						if( this_value.result == 1 ) { // we have valid responce
							if( this_value.action == 'alert' ) {
								alert(this_value.data);
							}
							else if( this_value.action == 'update_div_online_test_result' ) {
								//alert(this_value.data);
								setTimeout("$('#div_online_test_result b').html('"+this_value.data+"');", 700);
								//$('#div_online_test_result b').html(this_value.data);
							}
							else if( this_value.action == 'update_online_test_result' ) {
								//alert(this_value.data);
								//alert( $('.formApplication_JS input[name="online_test_result_value"]').val() );
								$('.formApplication_JS input[name="online_test_result_value"]').val(this_value.data);
								//alert( $('.formApplication_JS input[name="online_test_result_value"]').val() );
							}
							else if( this_value.action == 'check_online_test_result' ) {
								var online_test_min_result = $('.formApplication_JS input[name="online_test_min_result"]').val();
								var online_test_type = $('.formApplication_JS input[name="online_test_type"]').val();
								
								this_value.data = intval(this_value.data);
								online_test_min_result = intval(online_test_min_result);
								//alert(online_test_min_result);
								
								if( online_test_type == 2 ) { // mandatory
									if( this_value.data >= online_test_min_result ) {
										$('#warning_online_test').hide(); // fine! Now display the notice and the checkbox!
										
										// 2012-01-23 - Added an option to select - show or hide the text on success. We'll just leave the "success text" empty on page load, so no need to change anything here - //if( this_value.hide_ok_text == 'hide' ) { } else {
										$('#online_test_is_OK').show();
										
									}
									else {
										$('#warning_online_test').show(); // stop here! We may need to disable the button for checking the result.
										$('#online_test_is_OK').hide();
									}
								}
								else if( online_test_type == 1 ) { // mandatory
									$('#warning_online_test').hide();
									$('#online_test_is_OK').show(); // show a notice and continue...
								}
								
							}
							
						}
					});
					
				}
			});
			
			// rebuild the certificate_result select + rebind events
		}
		
	//});
}

// http://phpjs.org/functions/intval:435
function intval (mixed_var, base) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Matteo
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
    // *     example 5: intval('1e', 16);
    // *     returns 5: 30
    var tmp;

    var type = typeof(mixed_var);

    if (type === 'boolean') {
        return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var)) {
        return Math.floor(mixed_var);
    } else {
        return 0;
    }
}

function openNewOnlineTest()
{
	var errors = new Array();
	//errors.push('Test 1'); // test to add some error
	
	if( typeof online_test_url_to_open === 'undefined' ) {
		return false;
	}
	//alert(online_test_url_to_open);
	//return false;
	
	// Here we get some other values and add them to the URL as GET vars
		// - three names, date of birth, phone, email. Automatically fill: place of the exam - Online, <input type="hidden" name="course" value="Проверка на ниво" />
	var form_first_name_cyr = $('#form_first_name_cyr').val();
	var form_second_name_cyr = $('#form_second_name_cyr').val();
	var form_last_name_cyr = $('#form_last_name_cyr').val();
	var form_birthday_day = $('#form_birthday_day').val();
	var form_birthday_month = $('#form_birthday_month').val();
	var form_birthday_year = $('#form_birthday_year').val();
	var form_phone_1 = $('#form_phone_1').val();
	var form_phone_2 = $('#form_phone_2').val();
	var form_email = $('#form_email').val();
	var form_email_2 = $('#form_email_2').val();
	/*
	console.log(form_first_name_cyr);
	console.log(form_second_name_cyr);
	console.log(form_last_name_cyr);
	console.log(form_birthday_day);
	console.log(form_birthday_month);
	console.log(form_birthday_year);
	console.log(form_phone_1);
	console.log(form_phone_2);
	console.log(form_email);
	console.log(form_email_2);
	*/
	
	if( errors.length<1 ) { // no errors
		if( form_first_name_cyr=='' ) {
			errors[1] = 'Не сте въвели име на кирилица.';
		}
		if( form_second_name_cyr=='' ) {
			errors[2] = 'Не сте въвели презиме на кирилица.';
		}
		if( form_last_name_cyr=='' ) {
			errors[3] = 'Не сте въвели фамилия на кирилица.';
		}
		if( form_birthday_day=='' ) {
			errors[4] = 'Не сте въвели дата на раждане.';
		}
		if( form_birthday_month=='' ) {
			errors[5] = 'Не сте въвели месец на раждане.';
		}
		if( form_birthday_year=='' ) {
			errors[6] = 'Не сте въвели година на раждане.';
		}
		
		// check at least one phone is present
		if( form_phone_1=='' && form_phone_2=='' ) {
			errors[7] = 'Не сте въвели поне един телефон.';
		}
		else {
			// OK, we'll use the 'form_phone_1'. If it is empty, set the value from the form_phone_2 value
			if( form_phone_1=='' ) {
				form_phone_1 = form_phone_2;
			}
		}
		
		// check we have entered the emails and they are same
		if( form_email=='' || form_email_2=='' ) {
			if( form_email=='' ) {
				errors[8] = 'Не сте въвели e-mail.';
			}
			if( form_email_2=='' ) {
				errors[9] = 'Не сте въвели повторно e-mail.';
			}
		}
		else {
			if( form_email !== form_email_2 ) {
				errors[10] = 'Въведените e-mail адреси не съвпадат. Моля въведете валиден e-mail адрес!';
			}
		}
	}
	
	if( errors.length>0 ) {
		//alert(errors[0]);
		
		var alert_text = "Възникнаха грешки при стартирането на теста:\n";
		$.each( errors, function(index, value) { 
			//alert(index + ': ' + value); 
			if( typeof value !== 'undefined' ) { // do not show undefined indexes. JS auto adds the missing indexes...
				alert_text = alert_text + "\n- " + value;
			}
		});
		
		alert_text = alert_text + "\n\nМоля, коригирайте ги и натиснете бутона 'Стартирай тест' отново!";
		
		alert(alert_text);
		
	}
	else {
		
		// OK, everything is fine! Start the test!
		online_test_url_to_open_final = online_test_url_to_open;
		
		// GET option - the defauld one
		online_test_url_to_open_final = online_test_url_to_open_final + '&' +'birthday_date='+form_birthday_day + '-' + form_birthday_month + '-' + form_birthday_year;
		online_test_url_to_open_final = online_test_url_to_open_final + '&' +'form_phone='+form_phone_1;
		online_test_url_to_open_final = online_test_url_to_open_final + '&' +'form_email='+form_email;
		online_test_url_to_open_final = online_test_url_to_open_final + '&' +'name_cyr='+form_first_name_cyr + ' ' + form_second_name_cyr + ' ' + form_last_name_cyr; // add the name as last var, so if the name is too long and UTF8 it could be cut from some browsers...
		
		//alert(online_test_url_to_open_final);
		window.open( online_test_url_to_open_final ,'online_test_1','menubar=1,resizable=1,scrollbars=1,width=980,height=460');
		
		
		/* // POST option - tested under FF3.6, TODO - test under IE 6/7/8/9...
		// Add the values as post as the GET params are limited by some length
		// http://stackoverflow.com/questions/178964/javascript-post-on-form-submit-open-a-new-window
		var form = document.createElement("form");
		form.setAttribute("method", "post");
		form.setAttribute("action", online_test_url_to_open_final );
		
		// setting form target to a window named 'formresult'
		form.setAttribute("target", "online_test_1");
		
		// name_cyr
		var hiddenField = document.createElement("input");              
		hiddenField.setAttribute("name", 'name_cyr' );
		hiddenField.setAttribute("value", form_first_name_cyr + ' ' + form_second_name_cyr + ' ' + form_last_name_cyr);
		form.appendChild(hiddenField);
		document.body.appendChild(form);
		
		// birthday_date
		var hiddenField = document.createElement("input");              
		hiddenField.setAttribute("name", 'birthday_date' );
		hiddenField.setAttribute("value", form_birthday_day + '-' + form_birthday_month + '-' + form_birthday_year);
		form.appendChild(hiddenField);
		document.body.appendChild(form);
		
		// form_phone
		var hiddenField = document.createElement("input");              
		hiddenField.setAttribute("name", 'form_phone' );
		hiddenField.setAttribute("value", form_phone_1);
		form.appendChild(hiddenField);
		document.body.appendChild(form);
		
		// form_email
		var hiddenField = document.createElement("input");              
		hiddenField.setAttribute("name", 'form_email' );
		hiddenField.setAttribute("value", form_email);
		form.appendChild(hiddenField);
		document.body.appendChild(form);
		
		// creating the 'formresult' window with custom features prior to submitting the form
		window.open( online_test_url_to_open_final, 'online_test_1','menubar=1,resizable=1,scrollbars=1,width=980,height=460');
		
		form.submit();
		*/
		
	}
	
}




