var enable_text_gallery = 0;
$(document).ready(function() {
	if(enable_text_gallery == 1){   
		var options = { 
			insert : '#gallery_main_image',
			history : false,
			onImage : gallery_onImage,
			onThumb : gallery_onThumb
		};
		jQuery(function($) { $('ul.gallery').galleria(options); });		
	}
	var i = 0;
	while(document.getElementById('middle').getElementsByTagName('table')[i] && i < 10000){
		if (document.getElementById('middle').getElementsByTagName('table')[i].offsetWidth > document.getElementById('middle').offsetWidth - 400){
			document.getElementById('middle').getElementsByTagName('table')[i].className = 'wide';
		}
		i++;
	}

});

/******************************************
** TEXT GALLERY ** BEGIN
*******************************************/
function gallery_onImage(image,caption,thumb) { // let's add some image effects for demonstration purposes
	// fade in the image & caption
	image.css('display','none').fadeIn(1000);
	caption.css('display','none').fadeIn(1000);
	
	image.VerticalAlign();
	// fetch the thumbnail container
	var _li = thumb.parents('li');
	
	// fade out inactive thumbnail
	_li.siblings().children('img.selected').fadeTo(500,0.3);
	
	// scroll to active thumbnail
	$('#gallery_thumbnails .thumbnail_scroll').scrollTo(thumb, 800, {axis:'x',offset:-120});
	
	// fade in active thumbnail
	thumb.fadeTo('slow',1).addClass('selected'); 
	
	
	// add a title for the clickable image
	//image.attr('title','Next image >>');
};

function gallery_onThumb(thumb) { // thumbnail effects goes here
	// fetch the thumbnail container
	var _li = thumb.parents('li');
	
	// if thumbnail is active, fade all the way.
	var _fadeTo = _li.is('.active') ? '1' : '0.3';
	
	// fade in the thumbnail when finnished loading
	thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
	
	// hover effects
	thumb.hover(
		function() { thumb.fadeTo('fast',1); },
		function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
	)
};
function gallery_thumbnail_scroll(direction){
	if(direction > 0){
		$('#gallery_thumbnails .thumbnail_scroll').scrollTo('+=200px', 500, {axis:'x'});
	}
	else{
		$('#gallery_thumbnails .thumbnail_scroll').scrollTo('-=200px', 500, {axis:'x'});
	}
}
(function($) {
    $.fn.VerticalAlign = function(opts) {
        return this.each(function() {
            var top = (($(this).parent().height() - $(this).height()) / 2);
            $(this).css('margin-top', top);
        });
    };
})(jQuery);

function openImgPopUp(imgUrl, imgName){
	MyWindow = window.open(imgUrl,"Picture","toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1,width=400,height=400");
	MyWindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
	MyWindow.document.write('<html>');
	MyWindow.document.write('<head>');
	MyWindow.document.write('	<script type="text/javascript">');
	MyWindow.document.write('		function resizePopUp() {');
	MyWindow.document.write('			iWidth = document.documentElement.clientWidth;');
	MyWindow.document.write('			iHeight = window.innerHeight;');
	MyWindow.document.write('			if(iHeight == undefined) { iHeight = document.documentElement.clientHeight; }');
	MyWindow.document.write('			iWidth = document.images[0].width - iWidth;');
	MyWindow.document.write('			iHeight = document.images[0].height - iHeight;');
	MyWindow.document.write('			window.resizeBy(iWidth, iHeight);');
	MyWindow.document.write('		};');
	MyWindow.document.write('	</script>');
	MyWindow.document.write('	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');
	MyWindow.document.write('	<title>'+imgName+'</title>');
	MyWindow.document.write('</head>');
	MyWindow.document.write('<body style="margin:0; padding:0;" onLoad="resizePopUp();">');
	MyWindow.document.write('	<img src="'+imgUrl+'" alt="'+imgName+'" />');
	MyWindow.document.write('</body>');
	MyWindow.document.write('</html>');
	MyWindow.document.close();
	return(false);
}

function open_gallery(gallery_id, pic_id){
	window.open(g_web_url+'gallery.php?gallery_id='+gallery_id+'&pic_id='+pic_id, "Gallery", "toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=640,height=545");
	return false;
}
/******************************************
** TEXT GALLERY ** END
*******************************************/

/***************************************
** SYSTEM TOOLS
****************************************/
function Set_Cookie( name, value, expires, path, domain, secure ){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
	return true;
}

function createCookie(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=/";
}

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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function site_select_change(obj){
	window.location = obj[obj.selectedIndex].value;
}

// v1.5 - 2009.09.04 Ilmārs Mārciņš
//   first parameter "sObj" can be string or reference to "a" tag element with attribute "href"
function openPopUp(sObj, iWidth, iHeight) {
	if(isString(sObj)){
		var sUrl = sObj;
	}
	else{
		var sUrl = sObj.getAttribute('href');
	}
	window.open(sUrl, 'EditWindow', 'width='+iWidth+',height='+iHeight+',resizable=1,scrollbars=1');
	return false;
}
function isString(arg) {
	if (typeof arg == 'string') return true;
	if (typeof arg == 'object') {
		var criterion = arg.constructor.toString().match(/string/i);
		return (criterion != null);
	}
	return false;
}

// 2006.12.06 Ilmārs M.
// Atrod HTML tagu kas seko nākamais
function getPreviosTag(Me){
	var oNode = false;
	oNode = Me.previousSibling;
	while(1){
		if(oNode == false) break;
		if(oNode.nodeType == 1) break;
		oNode = oNode.previousSibling;
	}
	return oNode;
}

// 2006.12.06 Ilmārs M.
// Atrod iepriekšējo HTML tagu
function getNextTag(Me){
	var oNode = false;
	oNode = Me.nextSibling;
	while(1){
		if(oNode == false) break;
		if(oNode.nodeType == 1) break;
		oNode = oNode.nextSibling;
	}
	return oNode;
}

// 2006.12.06 Ilmārs M.
// Bīda HTML elementus uz augšu vai leju (maina tos vietām)
function moveElement(elementID, up, iKey){
	if(iKey != null) sKey = '_'+iKey;
	else sKey = '';
	var oMyOrder = document.getElementById('element_sort_order_'+elementID);
	var oMyRow = document.getElementById('element_entry_'+elementID);
	var totalCount = document.getElementById('element_total_count'+sKey).value;
	if((up == 1)&&((oMyOrder.value*1) > 1)){
		var oMyBrother = getPreviosTag(oMyRow);
		var brotherID = oMyBrother.getAttribute('element_id');
		oMyRow.parentNode.insertBefore(oMyRow, oMyBrother);
		oMyOrder.value = (oMyOrder.value*1) - 1;
		document.getElementById('element_sort_order_'+brotherID).value = (document.getElementById('element_sort_order_'+brotherID).value*1) + 1;
		document.getElementById('element_changed_'+elementID).value = 1;
		document.getElementById('element_changed_'+brotherID).value = 1;
	}
	if((up != 1) && ((oMyOrder.value*1) < (totalCount*1))){
		var oMyBrother = getNextTag(oMyRow);
		var brotherID = oMyBrother.getAttribute('element_id');
		oMyRow.parentNode.insertBefore(oMyBrother, oMyRow);
		oMyOrder.value = (oMyOrder.value*1) + 1;
		document.getElementById('element_sort_order_'+brotherID).value = (document.getElementById('element_sort_order_'+brotherID).value*1) - 1;
		document.getElementById('element_changed_'+elementID).value = 1;
		document.getElementById('element_changed_'+brotherID).value = 1;
	}
}
function needSave(elementID){
	document.getElementById('element_changed_'+elementID).value = 1;
}



/***************************************
** USER TOOLS
****************************************/
// pub_user_profile_edit
function pub_user_show_change_password(){
	var oHidd = document.getElementById('change_password_hidden');
	if(oHidd.value == '0'){
		document.getElementById('change_password_block').style.display = 'block';
		oHidd.value = '1';
	}
	else{
		document.getElementById('change_password_block').style.display = 'none';
		oHidd.value = '0';
	}
}

var show_hide_all_my_team_state = 0;
function show_hide_all_my_team(){
	if(show_hide_all_my_team_state == 0){
		$('.my_team:not(:first)').slideToggle('slow');
		show_hide_all_my_team_state = 1;
	}
	else{
		$('.my_team:not(:first)').slideUp('slow');
		show_hide_all_my_team_state = 0;
	}
}

/***************************************
** NEWS ** BEGIN
****************************************/
// comment_parameters[][0] - page
// comment_parameters[][1] - per_page
// comment_parameters[][2] - direction
var comment_parameters = [];

var comment_show_pic_comments = 0;
function news_gallery_show_pic(pic_id, direction, comment_type_p){
	if(pic_id < 0){
		pic_id = news_pic_selected+direction;
	}
	if((pic_id >= 0) && (pic_id < news_pics.length)){
		news_pic_selected = pic_id;
		var oDiv = document.getElementById('news_gallery');
		oDiv.style.backgroundImage = 'url(' + news_pics[news_pic_selected][0] + ')';
		oDiv.title = news_pics[news_pic_selected][1];
		// set download icon href
		$('#news_gallery a.overlay_download').attr('href', news_pics[news_pic_selected][2]);
		// remove active class
		$('#news_gallery_selector li').removeClass('active');
		$('#news_gallery_selector li:eq('+pic_id+')').addClass('active');
		$('#pic_description').html(news_pics[news_pic_selected][1]);

		if(comment_show_pic_comments == 1){
			$('#comment_type_id').val(news_pics[news_pic_selected][4]);
			$('#post_comment_form').show();
			$('#comment_text').val('');
			$('#ajax_post_done').hide();
			$.get('?', {comment_request:'ajax', comment_type:'user_gallery', comment_type_id:news_pics[news_pic_selected][4], comment_page:0, comment_per_page:comment_parameters[comment_type_p][1], comment_direction:comment_parameters[comment_type_p][2]}, comment_show_callback);
		}
	}
}

function comment_post_click(e, comment_type_p){
	e.preventDefault();

	if($('#comment_text').val().length == 0){
		return;
	}

	// AJAX post
	$.post("?", {comment_post:'ajax', comment_type:comment_type_p, comment_type_id:$('#comment_type_id').val(), comment_text:$('#comment_text').val()}, comment_post_callback);
	// Hide post form
	$('#post_comment_form').hide();
	// Show waiting line
	$('#comment_post_block p.ajax_post_wait').show();
}

function comment_post_callback(xml){
	// hide waiting line
	$('#comment_post_block p.ajax_post_wait').hide();
	// show finish line
	$('#comment_post_block p.ajax_post_done').show();
	var parts = [];
	parts = xml.split('{|}');
	if((parts.length == 4) && (parts[0] == 0)){
		// error free response. Must reload comment section box
		if(comment_parameters[parts[1]][2] == 'desc') {
			var comment_page_p = 0;
		}
		else{
			var comment_page_p = -1;
		}
		$.get('?', {comment_request:'ajax', comment_type:parts[1], comment_type_id:parts[2], comment_page:comment_page_p, comment_per_page:comment_parameters[parts[1]][1], comment_direction:comment_parameters[parts[1]][2]}, comment_show_callback);
	}
	$('#comment_post_block p.ajax_post_done').append(parts[3]);
}

function comment_show_callback(xml){
	var parts = [];
	parts = xml.split('{|}');
	if(parts.length == 2){
		$('#comment_container_'+parts[0]).html(parts[1]);
	}
}

function comment_show_page(comment_type_p, type_id, comment_page){
	comment_parameters[comment_type_p][0] = comment_page;
	$.get('?', {comment_request:'ajax', comment_type:comment_type_p, comment_type_id:type_id, comment_page:comment_parameters[comment_type_p][0], comment_per_page:comment_parameters[comment_type_p][1], comment_direction:comment_parameters[comment_type_p][2]}, comment_show_callback);
}

function comment_set_direction(obj, comment_type_p, type_id, direction){
	$('#comment_direction_select_'+comment_type_p+' a').removeClass('inactive');
	$(obj).addClass('inactive');

	comment_parameters[comment_type_p][2] = direction;
	Set_Cookie('comment_sort_order', direction, 90);
	comment_show_page(comment_type_p, type_id, 0);
}

function textarea_limit_length(obj, max_len, status_id){
	if(obj.value.length > max_len){
		obj.value = obj.value.substring(0, max_len);
	}
	if((status_id != undefined) && (status_id.length > 0)){
		$('#'+status_id).text(obj.value.length);
	}
}
/***************************************
** NEWS ** END
****************************************/

/***************************************
** CALENDAR ** BEGIN
****************************************/
function calendar_change_month(month_p, year_p){
	$.post("?", {calendar_change_month:'ajax', month:month_p, year:year_p}, calendar_change_month_callback);
	// Hide old calendar
	$('#small_calendar_container').hide();
	// Show waiting line
	//$('#small_calendar_wait').show();
}
function calendar_change_month_callback(xml){
	var parts = []
	parts = xml.split('{|}');
	if((parts.length == 2) && (parts[0] == '0')){
		// error free response
		// hide waiting line
		//$('#small_calendar_wait').hide();
		// populate calendar container with new data
		$('#small_calendar_container').html(parts[1]);
		// show calendar block
		$('#small_calendar_container').show();
	}
}
/***************************************
** CALENDAR ** END
****************************************/

/***************************************
** USER MESSAGES ** BEGIN
****************************************/
var message_show_status = [];
function message_show(message_id){
	if(message_show_status[message_id] == 1){
		// message alredy loaded, just show it
		$('#msg_body_'+message_id).show();
		message_show_status[message_id] = 2;
	}
	else if(message_show_status[message_id] == 2){
		// message alredy loaded, just hide it
		$('#msg_body_'+message_id).hide();
		message_show_status[message_id] = 1;
	}
	else{
		// make request
		$('#msg_body_'+message_id).show();
		$.post("?ajax=1&task=message&action=get_body", {message_id:message_id}, message_show_callback);
	}
}
function message_show_callback(xml){
	var parts = [];
	parts = xml.split('{|}');
	if((parts.length == 3) && (parts[0] == 0)){
		message_show_status[parts[1]*1] = 2;
		$('#msg_body_'+parts[1]).html(parts[2]);
		$('#message_item_'+parts[1]+' > a.head').removeClass('unread');
	}
}
function message_set_replay_recipient(u_id, u_name, subject){
	$('#new_msg_recievers').html('<span>' + u_name + '<input type="hidden" name="new_msg_reciever" id="new_msg_reciever" value="' + u_id + '" /></span> ');
	$('#new_msg_title').val(subject);
	$('#new_msg_body').val('');
	$('#new_message_form').show();
}
function message_delete(message_id){
	$('#message_item_'+message_id).slideUp('fast');
	$('#message_item_'+message_id).remove();
	$.post("?ajax=1&task=message&action=delete", {message_id:message_id});
}
function new_message_post_click(e){
	e.preventDefault();

	if(($('#new_msg_body').val().length == 0) && ($('#new_msg_title').val().length == 0)){
		return;
	}
	// AJAX post
	$.post("?ajax=1&task=message&action=post_message", {msg_reciever:$('#new_msg_reciever').val(), msg_title:$('#new_msg_title').val(), msg_body:$('#new_msg_body').val()}, new_message_post_callback);
	// Hide post form
	$('#new_message_form').hide();
	// Show waiting line
	$('#new_message_block p.ajax_post_wait').show();
}

function new_message_post_callback(xml){
	// hide waiting line
	$('#new_message_block p.ajax_post_wait').hide();
	// show finish line
	$('#new_message_block p.ajax_post_done').show();
	var parts = []
	parts = xml.split('{|}');
	if((parts.length == 2) && (parts[0] == 0)){
		// error free response. Show OK status
		$('#new_message_block p.ajax_post_done').html(parts[1]);
	}
}

/***************************************
** USER MESSAGES ** END
****************************************/

function changeTextSize(tSize){ 
	tSize = tSize*1;

	oMainColumn = document.getElementById('center'); 
	var h1Length = oMainColumn.getElementsByTagName('h1').length;
	var pLength = oMainColumn.getElementsByTagName('p').length;
	var spanLength = oMainColumn.getElementsByTagName('span').length;
	
	if(tSize == 0){
		oMainColumn.style.fontSize = '13px';
		
		for (var i = 0; i < h1Length; i++){
			oMainColumn.getElementsByTagName('h1')[i].style.fontSize = '18px';
		}
		createCookie('saved_text_size', tSize, 120);
	}
	else if (tSize == 1){
		oMainColumn.style.fontSize = '16px';
		
		for (var i = 0; i < h1Length; i++){
			oMainColumn.getElementsByTagName('h1')[i].style.fontSize = '21px';
		}
		createCookie('saved_text_size', tSize, 120);
	}
	else if (tSize == 2){
		oMainColumn.style.fontSize = '18px';
		
		for (var i = 0; i < h1Length; i++){
			oMainColumn.getElementsByTagName('h1')[i].style.fontSize = '23px';
		}
		createCookie('saved_text_size', tSize, 120);
	}
	
	for (var i = 0; i < pLength; i++){
		oMainColumn.getElementsByTagName('p')[i].style.fontSize = '';
	}
	
	for (var i = 0; i < spanLength; i++){
		oMainColumn.getElementsByTagName('span')[i].style.fontSize = '';
	}	
		
	document.getElementById('controls').style.fontSize = '13px';
}


/***************************************
** DIFFERENT - Viktorija Lagutina
****************************************/

function cleanInputContent(id, defaultText){
	if (document.getElementById(id).value == defaultText){
		document.getElementById(id).value = '';
	}
}

function setInputDefault(id, value, condition){
	switch (condition){
		case 'empty': //only if user hasn't filled field
			if (document.getElementById(id).value == ''){
				document.getElementById(id).value = value;
			}
			break;
		case 'all': //set to default even if filled
		default:
			document.getElementById(id).value = value;
			break;
	}
}
function searchWith1189(value, defaultText){	
	if (value != '' && value != defaultText){
		value = encodeURI(value);
		window.open('http://1189.lv/1189lv:search:view,query:vieta%3asalacgr%C4%ABvas+' + value);
	}
}

function is_valid_phone(value){
	if (value.length > 13 || value.length < 8 || !value.match(/^([+]{1}[0-9]{3}(\s){0,1}){0,1}[0-9]{8}$/)){
		return false;
	}
	else{
		return true;
	}
}

function is_valid_price(value){
	if (value.length <= 0 || !value.match(/^[0-9]*[.|,]{0,1}[0-9]*$/)){
		return false;
	}
	else{
		return true;
	}
}

function is_valid_text(value){
	if (value.length < 10){
		return false;
	}
	else{
		return true;
	}
}


function openAdvert(url){ //open advertisement popup
	window.open(url, 'ad', 'toolbar=0,location=0,status=0,menubar=0,scrollbars=1,resizable=1,width=700,height=700');
	return false;
}

function valideAll(){ //valide advertisement before sending to server
	if (is_valid_phone(document.getElementById('contact_phone').value) && is_valid_price(document.getElementById('price').value) && is_valid_text(document.getElementById('adv').value)){
		return true;
	}
	return false;
}
/***************************************
** DIFFERENT ** END
****************************************/
