var next_focus = '';

/**
 * Executed when document is finished loading elements into DOM
 */
$(document).ready(function() {

	//$('input, textarea').placeholder();

	$(document).keyup(function(e) {
	  if (e.keyCode == 27) {
			if ($('#confirm').length) {
				closeConfirmBox();
			} else if ($('#alert').length) {
				closeAlertBox();
			}
		}
	});

	// replace all emails to js. if js is turned off, users and bots see email[at]domain.ltd
	$('.email').each(function(){
		var email = $(this).text().replace('[at]', '@');
		$(this).html('<a href="mailto:'+email+'">'+email+'</a>');
	});

	$('.confirm').click(function(){
		confirmBox($(this).attr('href'), $(this).attr('rel'));
		return false;
	});

	rebindHelpboxes();


	$('.print').click(function(){
		if (!$(this).hasClass('nojs')) {
			window.print();
			return false;
		}
	});

	$('.back').click(function(){
		history.go(-1);
		return false;
	});

	jQuery.gsuggest();

	$('form.ajax').ajaxForm({
		success: function(data, jqForm, options){
			$(options).append(data);
			$(options).find('.container:first').slideUp(400, function(){
				$(options).find('.container:first').remove()

				if(typeof(app) != 'undefined' && app == 'draugiem') {
					draugiemResizeIframe();
				}
			});
			$(options).find('.container:last').hide().slideDown();
			rebindDatepicker();
		},
		beforeSubmit: function(arr, $form, options) {
			if ($form.find('#CvSave').val() == '1') {
				var elements = $form.find(
					'.required input[type=text], .required select, #tbl_computer_skills input[type=text]'
				);

				// darba pieredze: ja nav ieķeksēts "strādāju joprojām", tad pieliekam datuma lauku pārbaudēm
				$form.find('.still-working input[type=hidden]:first-child').each(function() {
					if (!parentsHasClass($(this), 'prototype')) {
						if ($(this).val() != '1') {
							$(this).parent().siblings('select').each(function(){
								elements.push($(this))
							});
						}
					}
				});

				for (i=0; i<elements.length; i++) {
					if (!parentsHasClass($(elements[i]), 'prototype')) {
						if ($(elements[i]).val() == '' || $(elements[i]).val() == '0') {
							label = getLabel(elements[i]);
							if (label.length) {
								message = 'Lūdzu, aizpildiet lauku "'+label+'"';
							} else {
								message = 'Lūdzu, aizpildiet šo lauku';
							}
							if(typeof(app) != 'undefined' && app == 'draugiem') {
								alertBox(message, false, elements[i], elements[i]);
							} else {
								alertBox(message, false, elements[i]);
							}
							return false;
						} else if ($(elements[i]).hasClass('num') && !isNumeric($(elements[i]).val())) {
							label = getLabel(elements[i]);
							if (label.length) {
								message = 'Lūdzu, aizpildiet lauku "'+label+'" ar skaitli';
							} else {
								message = 'Lūdzu, aizpildiet šo lauku ar skaitli';
							}
							if(typeof(app) != 'undefined' && app == 'draugiem') {
								alertBox(message, false, elements[i], elements[i]);
							} else {
								alertBox(message, false, elements[i]);
							}
							return false;
						}
					}
				}
			}

			return true
		}
	});

	$('a.wnd').fancybox({
		hideOnContentClick: false
	});

	if(typeof(app) != 'undefined' && app == 'draugiem') {
		$('a.suggest').click(function(){
			draugiemWindowOpen($(this).attr('href'), 500, 305);
			return false;
		});
	} else {
		$('a.suggest').fancybox({
			hideOnContentClick: false,
			autoDimensions: false,
			autoScale: false,
			scrolling: 'no',
			height: 305,
			width: 500,
			onComplete : function(){
				bindSuggestForm();
			}
		});
	}

	rebindDatepicker();

	$('#PostActiveTill').datepicker({
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		onSelect: function(dateText, inst) {
			$('#PostActiveTillHrf').val('0');
			$('#PostActiveTillHrf option').each(function(){
				if (dateText == $(this).val()) {
					$('#PostActiveTillHrf').val(dateText);
					return;
				}
			});
		}
	});

	if ($('#PostActiveTillHrf').length) {
		dateText = $('#PostActiveTill').val();
		$('#PostActiveTillHrf option').each(function(){
			if (dateText == $(this).val()) {
				$('#PostActiveTillHrf').val(dateText);
				return;
			}
		});
	}

	if ($('#PostCountryId').length) {
		checkPostCountry();
	}

	if($('.scrollable').length) {
		$('table tr.local').shuffle();

		if($('.scrollable .items a').length > 7) {
			$('.scrollable').scrollable({
				circular: true,
				keyboard: false,
				speed: 700
			}).autoscroll({
				interval: 7000
			});
			$('.scrollable').scrollableAddClones();

			$('#premium-companies .right').hover(function(){
				$('.scrollable').data('scrollable').stop();
			}, function(){
				$('.scrollable').data('scrollable').play();
			});

			$('#premium-companies .left').hover(function(){
				$('.scrollable').data('scrollable').stop();
			}, function(){
				$('.scrollable').data('scrollable').play();
			});
		}
		/*$('.scrollable div img').each(function(){
			if($(this).height() < $(this).parent().height()) {
				$(this).css('margin-top', (($(this).parent().height() - $(this).height()) / 2));
			}
		});*/
	}

	if ($('.posts').length) {
		$('.posts tr td').removeClass('first').removeClass('last');
		/*$('.posts tbody tr td').css('border-top', false);
		$('.posts tbody tr:first td').css('border-top', '1px solid #fff');*/
		$('.posts tr td:first-child').addClass('first');
		$('.posts tr td:last-child').addClass('last');
	}
	
	$('.image_remove').hide();

	$('a.start-tab').live('click', function() {
		$('a.start-tab').removeClass('active');
		$(this).addClass('active');
		$('#start-posts').fadeTo(200, 0.4);
		$('#start-posts').load($(this).attr('href'), function() {
			$(this).fadeTo(400, 1);
		});
		return false;
	});
	
	$('#start-posts #ajax-content #paginator a').live('click', function() {
		$('#start-posts').fadeTo(200, 0.4);
		$('#start-posts').load($(this).attr('href'), function() {
			$(this).fadeTo(400, 1);
		});
		return false;
	});

});

function rebindHelpboxes() {
	$('.help').unbind().click(function(){
		if(typeof(app) != 'undefined' && app == 'draugiem') {
			alertBox($(this).attr('rel'), true, false, $(this));
		} else {
			alertBox($(this).attr('rel'));
		}
		return false;
	});
}

/**
 * Atrodam elementam labeli un nogriežam beigu * un/vai :
 *
 * @param object el Element
 * @return text
 */
function getLabel(el) {
	labels = $(el).siblings('label');

	if (labels.length == 1) {
		label = labels.text();

		if (label.substr(-1, 1) == ':' || label.substr(-1, 1) == '*') {
			label = label.substr(0, label.length-1);
		}

		if (label.substr(-1, 1) == ':' || label.substr(-1, 1) == '*') {
			label = label.substr(0, label.length-1);
		}

		return label;
	}

	return ''
}

function changePostActiveTill(date) {
	if (date != '0') {
		$('#PostActiveTill').val(date);
	}
}

function bindSuggestForm() {
	$('#PostSuggestion').ajaxForm({
		success: function(data, jqForm, options){
			$('#fancybox-inner').html(data);
			bindSuggestForm();
		}
	});
}

/**
 * Pārbaudam vai kāds no elementa vecākiem ir ar norādīto klasi
 */
function parentsHasClass(el, className) {
	el = el.parent();
	while (el.length) {
		if (el.hasClass(className)) {
			return true;
		}
		el = el.parent();
	}
	return false;
}

function rebindDatepicker() {
	$(".calendar").each(function(){
		$(this).datepicker('destroy');
		if (!parentsHasClass($(this), 'prototype')) {
			$(this).datepicker({
				dateFormat: 'yy-mm-dd'
			});
		}
	});
}

/**
 * Redirect user to specified page
 *
 * @param string url Address to redirect to
 */
function redirect(url) {
	document.location = url;
}

/**
 * Print email link (protection from spambots)
 * If javascript is disabled, nothing is visible
 *
 * @param string p1 Part 1 - this is username
 * @param string p2 Part 2 - this is domain and TLD
 * @param string name (optional) Display value
 */
function writemail(p1, p2, name) {
	if (typeof(name) == "undefined") {
		name = p1+"@"+p2;
	}

	document.write("<a href='mailto:"+p1+"@"+p2+"'>"+name+"</a>");
}

/**
 * Show/hide search box
 */
function toggleSearchbox() {
	if ($('#searchbox').height() > 30) {
		var remember = ($('#searchbox .toggler').attr('rel') == 'remember');
		$('#searchbox').animate({
	    height: '25px'
	  }, 700, function() {
	    $('#searchbox .toggler').addClass('closed');
	    $('#searchbox .toggler span').toggle();
	    if (remember) {
				$.ajax({
					url: webroot+"ws/searchbox/hidden",
					cache: false
				});
			}
	  });
		$('#searchbox form').fadeOut(700);
	} else {
		var remember = ($('#searchbox .toggler').attr('rel') == 'remember');
		$('#searchbox').animate({
	    height: '70px'
	  }, 700, function() {
	    $('#searchbox .toggler').removeClass('closed');
	    $('#searchbox .toggler span').toggle();
	    if (remember) {
				$.ajax({
					url: webroot+"ws/searchbox/visible",
					cache: false
				});
			}
	  });
	  $('#searchbox form').fadeIn(700);
	}
}

/**
 * Pievienojam tabulai jaunu ierakstu par pamatu ņemot 1, kā arī iztīram jaunās rindas teksta laukus
 */
function addDataRow(table, row) {
	new_row = $(row).clone();
	new_row.find('input[type=text], textarea').val('');
	new_row.find('select').removeAttr('selected');
	$(table).append(new_row);
	resetNumbering(table);
	rebindDatepicker();
	if(typeof(app) != 'undefined' && app == 'draugiem') {
		draugiemResizeIframe();
	}
}

/**
 * Pievienojam tabulai jaunu ierakstu par pamatu ņemot 1
 */
function delDataRow(tr) {
	table = $(tr).parent();
	$(tr).remove();
	resetNumbering(table);
	if(typeof(app) != 'undefined' && app == 'draugiem') {
		draugiemResizeIframe();
	}
}

/**
 * Pārģenerējam tabulas rindu numerāciju. NUmerācija sākas no 2. rindas (1)
 *
 * @param string table Tabulas selektors
 */
function resetNumbering(table) {
	num = 0
	$(table).find('tr').each(function(i){
		td = $(this).find('td.num');
		if (td.length == 1) {
			td.text(++num + '.');
		}
	});
}

/**
 * Pievienojam sludinājuma sadaļu pievienošanas lapā
 */
function addPostSection() {
	var item = $('.prototype .item').clone();
	$('#post-sections').append(item);
	$('#post-sections .item:last').hide().slideDown(300);
	rebindHelpboxes();
}

/**
 * Izdzēšam html elementu no lapas
 */
function removeBlock(el) {
	$(el).slideUp(300, function(){
		$(el).remove();
	});
}

function hideAllBlocks()
{
	$('#text_info').slideUp(300);
	$('a.image_remove').show();
}
function showAllBlocks()
{
	$('#text_info').slideDown(300);
	$('.image_input_container').html($('.image_input_container').html());
	$('a.image_remove').hide();
}

/**
 * Ielādējam pieteikumus sludinājumam uzņēmuma modulī
 *
 * @param int post_id Sludinājuma ID
 */
function loadApplications(post_id) {
	if ($('#application-'+post_id).text() == '') {
		$.ajax({
			url: webroot+'posts/applications/'+post_id,
			cache: false,
			success: function(data) {
				$('#application-'+post_id).html(data).slideToggle();
			}
		});
	} else {
		$('#application-'+post_id).slideToggle();
	}
}

function updateStillWorking(chk) {
	$(chk).siblings('input[type=hidden]').val(chk.checked ? '1' : '0')

	if (chk.checked) {
		//$(chk).parent().siblings('select').attr('disabled', 'disabled');
		$(chk).parent().siblings('select').hide();
	} else {
		//$(chk).parent().siblings('select').removeAttr('disabled');
		$(chk).parent().siblings('select').show();
	}
}

function isNumeric(input) {
	return (input - 0) == input && input.length > 0;
}


/**
 * Parādam izlecošo logu ar "Jā" (aiziet uz norādīto url) un Nē" (aizver logu) pogām
 *
 * @param string url URL to redirect if user chooses yes
 * @param string text (optional) Text to show
 */
function confirmBox(url, text) {
	closeConfirmBox(false); // close previous box (if any)

	if (text == '' || typeof(text) == 'undefined') {
		text = 'Vai tiešām vēlaties veikt šo darbību?';
	}

	var html = '<div id="confirm-bg"></div><div id="confirm"><h2>Uzmanību!</h2><p>'+text+'</p>\
		<div class="controls"><a href="'+url+'" class="button agree big" onclick="closeConfirmBox()">Jā, turpināt</a>\
		<a href="javascript:void(0)" class="button cancel" onclick="closeConfirmBox()">Nē, atcelt</a></div></div>';

	$("body").append(html);

	$('#confirm, #confirm-bg').fadeIn();

	var x = Math.round(($("body").width() - $("#confirm").width()) / 2);
	var y = Math.round(($("body").height() - $("#confirm").height()) / 2 );

	$("#confirm").css("left", x+"px");
	$("#confirm").css("top", y+"px");
}

/**
 * Aizver izlecoso logu
 */
function closeConfirmBox(animate) {
	if (typeof(animate) == 'undefined' || animate) {
		$('#confirm, #confirm-bg').fadeOut('normal', function(){
			$(this).remove();
		});
	} else {
		$('#confirm, #confirm-bg').remove();
	}
}


/**
 * Parādam izlecošo logu ar informācijas tekstu
 *
 * @param string text Text to show
 */
function alertBox(text, success, focus_element, position_element) {
	closeAlertBox(false); // close previous box (if any)

	if (typeof(success) != 'undefined' && !success) {
		attr = ' class="error"';
	} else {
		attr = '';
	}

	if (typeof(focus_element) != 'undefined') {
		next_focus = focus_element;
	}

	var html = '<div id="confirm-bg"></div><div id="alert"'+attr+'><p>'+text+'</p>\
		<a href="javascript:void(0)" class="close" onclick="closeAlertBox()">Aizvērt</a></div>';

	$("body").append(html);

	$('#alert, #confirm-bg').fadeIn();

	var x = Math.round(($("body").width() - $("#alert").width()) / 2);

	if (typeof(position_element) != 'undefined') {
		var pos = $(position_element).offset();
		var y = Math.round(pos.top - $("#alert").height() / 2 );
	} else {
		var y = Math.round(($("body").height() - $("#alert").height()) / 2 );
	}

	$("#alert").css("left", x+"px");
	$("#alert").css("top", y+"px");
}

/**
 * Aizver izlecoso logu
 */
function closeAlertBox(animate, focus_element) {
	if (typeof(animate) == 'undefined' || animate) {
		$('#alert, #confirm-bg').fadeOut('normal', function(){
			$(this).remove();
			if (typeof(next_focus) == 'object') {
				next_focus.focus();
				next_focus = '';
			}
		});
	} else {
		$('#alert, #confirm-bg').remove();
		if (typeof(next_focus) == 'object') {
			next_focus.focus();
			next_focus = '';
		}
	}
}

function deleteStep2() {
	$('#delete-step1').slideUp(400);
	$('#delete-step2').slideDown(400, function(){
		if(typeof(app) != 'undefined' && app == 'draugiem') {
			draugiemResizeIframe();
		}
	});
}

function removeCompanyCategory(el) {
	$(el).parent().slideUp(200, function(){
		$(this).remove();
	})
}

function addCompanyCategory(parent_s) {
	$(parent_s+" .input:first-child").clone().appendTo(parent_s);
	$(parent_s+" .input:last select").val('0');
}

function checkPostCountry() {
	if ($("#PostCountryId").val() != '99') {
		$("#PostCityId").attr('disabled', true);
	} else {
		$("#PostCityId").removeAttr('disabled');
	}
}

(function($){
    $.fn.shuffle = function() {
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
        return $(shuffled);
    };
})(jQuery);

/**
 * Vienkārša funkcija, kas ieseto cookie uz X dienām. Default 0
 */
function setCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


/**
 * Fu-ja nolasa cookie vērtību
 */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


/**
 * Slīdošā lenta
 */
$.fn.catfish = function(options) {
	if(options.name == undefined) options.name = 'catfish';
	if(options.close_button == undefined) options.close_button = false;
	if(options.height == undefined) options.height = 35;
	if(options.target == undefined) options.target = '_blank';
	if(options.days == undefined) options.days = 30;

	var close_btn = '';

	if (options.close_button) {
		close_btn = '<a href="javascript:void(0)" class="close" onclick="$(\'#catfish\').fadeOut(100); setCookie(\'' + options.name + 'BannerHide\', true, ' + options.days + ');">Aizvērt</a>';
	}

	var banner = $('<div class="catfish-outer"></div>')
		.height(options.height)
		.append($('<div class="catfish-overlay"></div>')
			.height(options.height)
			.append($('<div class="catfish-inner"></div>')
				.height(options.height)
				.append(close_btn)
				.append($('<a href="' + options.url + '" class="cb" target="' + options.target + '">&nbsp;</a>')
					.height(options.height)
					.css('background', 'url("' + options.img + '") repeat-x scroll 0 0 transparent')
				)
			)
		);
	$(this).html(banner);
	el = $(this).find('a.cb');
	width = options.width;
	setInterval('moveCatfish(el, width)', 50);
};

var catfishpos = 1;
function moveCatfish(el, width) {
	$(el).css('background-position', '-' + catfishpos + 'px 0');
	if(catfishpos == width) {
		catfishpos = 1
	} else {
		catfishpos += 1;
	}
}
