/*
		 ---------------------- Some small functions
*/

/* this function trim spaces the left of string */
function ltrim(str) {
    return str.replace(/^\s+/,'');
};

/* this function trim spaces the right of string */
function rtrim(str) {
    return str.replace(/\s+$/,'');
};

/* this function trim spaces the left and right of string */
function trim(str) {
	return ltrim(rtrim(str));
};

/* this function show block on click */
function showBlock(openLink, block) {
    document.getElementById(block).style.display = 'block';
    document.getElementById(openLink).style.display = 'none';
};

/* this function hide block on click */
function hideBlock(openLink, block) {
    document.getElementById(block).style.display = 'none';
    document.getElementById(openLink).style.display = 'block';
};

/* this function scroll window down to the block */
function gotoWorkshopBlock(url) {
	try {
		var url_list = url.split('/');
		var number_list = url_list[4].split('#workshop-block');
		$('#workshop-link'+number_list[1] + ' a').click();
		$.scrollTo('#workshop-block'+number_list[1]); 
	} catch (e) {
		return false;
	};
};

/* this function show additional field for selection field */
function onVacancyChange(selectId, spanId, fieldId) {
    var select = document.getElementById(selectId);
    var span = document.getElementById(spanId);
    var field = document.getElementById(fieldId);

    if (select.options[select.selectedIndex].text == 'Другая вакансия') {
        span.style.display = 'inline';
    } else {
        span.style.display = 'none';
		$('#'+fieldId).addClass('inactive');
        field.value = 'Другая вакансия';
    };
};

/* this funciton return array with label of the text of the checked checkbox */
function getTextOfCheckedCheckbox(mainElement, labelPrefix) {
	var list = new Array();
	$('#' + mainElement + ' input:checkbox:checked').each(function() {
		list.push($('#' + labelPrefix + $(this).attr('id')).text());
	});
	return list;
};

/* this function bind click and hover events of the image on project page */
var timer
function initProjectImageView() {
	$("#thumbnail li img").click(function() {
		$("#large").attr("src", $(this).attr("src"));
		$(this).addClass("image_active");
		$(this).fadeTo("fast", 1);
		updateImageDivClass();
	});

	$("#thumbnail li img").hover(
		function() {
			timer = setTimeout("addActiveClass('" + $(this).attr("id") + "')", 200);
		}, function() {
			clearTimeout(timer);
			if ($(this).attr("src") != $("#large").attr("src")) {
				//$(this).removeClass("image_active");
				$(this).fadeTo("fast", 0.5);
			};
		}
	);
};

/* this function set image_active class of the image */
function  addActiveClass(id) {
	$("#" + id).fadeTo('fast', 1);
	//$("#" + id).addClass("image_active");
};

/* this function update class of the div on project page */
function updateImageDivClass() {
	$("#thumbnail li img").each(function() {
		if ($(this).attr("src") == $("#large").attr("src")) {
			$(this).fadeTo("fast", 1);
			$(this).addClass("image_active");
		} else {
			$(this).removeClass("image_active");
			$(this).fadeTo("fast", 0.5);
		};
	});
};

/* this function valid question, order, vacancies forms */
function validForm(name, is_vacancy) {
	var flag = true
	if (is_vacancy) {
		$('#' + name + '-form input').each(function() {
			if ($(this).attr('class') == 'inactive') {
				if ($(this).attr('id') == 'other_vacancies') {
					if ($('#vacancy').val() == 'Другая вакансия')
						flag = false;
				} else 
					flag = false;
			};
		});	
	} else {
		$('#' + name + '-form input').each(function() {
			if ($(this).val() == '')
				flag = false;
		});
	};
	
	if ($('#' + name + '_info').attr('class') == 'inactive' && is_vacancy)
		flag = false;
	else if ($('#' + name + '_info').val() == '')
		flag = false;
	
	if (flag)
		$('#' + name + '-form').submit();
	else {
		alert('Заполните, пожалуйста, все поля')
		return false;
	};
};

/*
		 ---------------------- Functions work with 'input type=file'
*/

var tableRowNumber = 1;

/* this funciton add new row on table with id = tableId */
function addNewRow(divId, maxCount) {
	var div = document.getElementById(divId);
	var table;
	
	if (!document.getElementById('fileContainer')) {
		table = document.createElement('table');
		table.setAttribute('id', 'fileContainer');
		div.appendChild(table);
	} 
	
	table = document.getElementById('fileContainer');
		
    var rowsCount = table.rows.length;
	
	if (rowsCount == maxCount-1) {
		document.getElementById('add_file').style.cssText = 'display: none;';
	}

    if (rowsCount < maxCount) {
        var newRow = table.insertRow(rowsCount);
        newRow.setAttribute('id', 'row' + tableRowNumber);

        var firstCell = newRow.insertCell(newRow.cells.length);
        var secondCell = newRow.insertCell(newRow.cells.length);
		
		// create input type='file'
        var input = document.createElement('input');
        input.setAttribute('type', 'file');
        rowsCount++;
        input.setAttribute('name', 'file' + rowsCount);
        input.setAttribute('id', 'file' + rowsCount);

        firstCell.appendChild(input);
        
		// create image
        var image = document.createElement('img');
        image.setAttribute('src', '../media/img/delete.png');
        image.setAttribute('style', 'margin-left: 4px; cursor: pointer; cursor: hand;');
        image.setAttribute('title', 'Удалить');
        image.onclick = function(){deleteRow(newRow);};

        secondCell.appendChild(image);
        
        tableRowNumber++;
    }
};

/* this function delete row */
function deleteRow(tr) {
    tr.parentNode.removeChild(tr);
    changeAttributeFile(document.getElementById('fileContainer'));
	document.getElementById('add_file').style.cssText = 'display: inline;';
	
	var table = document.getElementById('fileContainer');
	var anchorText = document.getElementById('add_file').innerHTML;
	if (table.rows.length == 0) {
		table.parentNode.removeChild(table);
		if (anchorText == 'Прикрепить еще один файл') {
			document.getElementById('add_file').innerHTML = 'Прикрепить файл';
		} else if (anchorText == 'Прикрепить еще один файл (техническое задание)') {
			document.getElementById('add_file').innerHTML = 'Прикрепить файл (техническое задание)';
		}
	}
};

/* this function change attribute 'id' and 'name'
   in the all 'input type=file' elements */
function changeAttributeFile(table) {
    var inputs = table.getElementsByTagName('input');
    for (i = 0; i < inputs.length; i++) {
        id = i + 1;
        inputs[i].setAttribute('name', 'file' + id);
        inputs[i].setAttribute('id', 'file' + id);
    }
};

/*
	 ---------------------- Functions for work with menu
*/

var submenu = new Array('solutions', 'clients', 'company');

/* this function show/hide dropdown menu */
function showSubmenu(mainMenu) {
    var timer = 0;
    var subMenu = '.pop-menu-'+mainMenu;
	
     /* action for menu */
    $('#'+mainMenu).hover(
        function() {
            $(subMenu).show();
        },
        function() {
            timer = setTimeout("$('"+subMenu+"').hide()", 0);
        }
    );

    /* action for submenu */
    $(subMenu).hover(
        function() {
            clearTimeout(timer);
            $(subMenu).show();
        },
        function() {
            $(subMenu).hide();
        }
    );
};

/* this function define current menu */
function defineCurrentMenu() {
	$('#menu a').each(function () {
		href = $(this).attr('href').replace(/\//g,'');
		if (window.location.href.indexOf(href) > 0) {
			// hide menu link
			$(this).hide();
			// show menu text
			$(this).parent().find('p').show();
			// add class current to menu
			$(this).parent().addClass('current');
			return;
		}
	});
};
