var g_host = location.host;
var g_protocol = location.protocol;
//var g_hostname = location.hostname;

var g_protocol_host = g_protocol + '//' + g_host;


//--- function for tablesorter -----

$(document).ready(function(){
// ---- tablesorter -----
$("#id_tablesorter").tablesorter({
//	sortList:[[0,1]],
	widgets: ['zebra']
});
// ---- tablesorter -----
});

//--- /function for tablesorter -----


function existElement(elname) {

		if (document.getElementById(elname)) return true;
		if (document.getElementsByName(elname).length) return true;

	return false;
}

function getElement(elname) {

		if (document.getElementById(elname)) return document.getElementById(elname);
		if (document.getElementsByName(elname)) return document.getElementsByName(elname)[0];
}

function changeDisplayStyle(elname) {

		if (existElement(elname))
			if (getElement(elname).style.display == 'none')
				getElement(elname).style.display = '';
			else
				getElement(elname).style.display = 'none';
}



function checkEmail(string){
	return string.match(/^[\w-\.]+@[\w-\.]+\.\w{2,4}$/ig);
}


function check_form_advertisement()	{
	
	error_count = 0;
	if ($('#tipas').val() == '0')	{
		$('#tipas').after($('<span class="error" style="color:red"> Išrinkite skelbimo tipą.</span>'));
		error_count++;
	}

	if (!$('#vardas').val())	{
		$('#vardas').after($('<span class="error" style="color:red"> Įveskite savo vardą.</span>'));
		error_count++;
	}

	if (!$('#email').val())	{
		$('#email').after($('<span class="error" style="color:red"> Įveskite el. paštą.</span>'));
		error_count++;
	}

	if (!$('#tel').val())	{
		$('#tel').after($('<span class="error" style="color:red"> Įveskite telefoną.</span>'));
		error_count++;
	}

	if ($('#email').val() && !checkEmail($('#email').val()))	{
		$('#email').after($('<span class="error" style="color:red"> Klaidingas el. paštas.</span>'));
		error_count++;
	}

	if (error_count > 0)
		return false;

}


function check_form_question()	{
	
	error_count = 0;

	if (!$('#vardas').val())	{
		$('#vardas').after($('<span class="error" style="color:red"> Įveskite savo vardą.</span>'));
		error_count++;
	}

	if (!$('#email').val())	{
		$('#email').after($('<span class="error" style="color:red"> Įveskite el. paštą.</span>'));
		error_count++;
	}

	if (!$('#tel').val())	{
		$('#tel').after($('<span class="error" style="color:red"> Įveskite telefoną.</span>'));
		error_count++;
	}

	if ($('#email').val() && !checkEmail($('#email').val()))	{
		$('#email').after($('<span class="error" style="color:red"> Klaidingas el. paštas.</span>'));
		error_count++;
	}

	if (!$('#klausimas').val())	{
		$('#klausimas').after($('<span class="error" style="color:red"> Įveskite klausimą.</span>'));
		error_count++;
	}

	if (error_count > 0)
		return false;

}

function check_form_message_send()	{
	
	error_count = 0;

	if (!$('#vardas').val())	{
		$('#vardas').after($('<span class="error" style="color:red"> Įveskite savo vardą.</span>'));
		error_count++;
	}

	if (!$('#email').val())	{
		$('#email').after($('<span class="error" style="color:red"> Įveskite el. paštą.</span>'));
		error_count++;
	}

	if (!$('#tel').val())	{
		$('#tel').after($('<span class="error" style="color:red"> Įveskite telefoną.</span>'));
		error_count++;
	}

	if ($('#email').val() && !checkEmail($('#email').val()))	{
		$('#email').after($('<span class="error" style="color:red"> Klaidingas el. paštas.</span>'));
		error_count++;
	}

	if (!$('#tekstas').val())	{
		$('#tekstas').after($('<span class="error" style="color:red"> Įveskite tekstą.</span>'));
		error_count++;
	}

	if (error_count > 0)
		return false;

}


function record_edit(record_type, record_id)	{

g_record_type = record_type;
g_record_id   = record_id;

// record_type - 1	kalbos		table languages
// record_type - 2	apie mus	table languages
// record_type - 3	kontaktai	table languages
// record_type - 4	svarstykles	table menu_sub
// record_type - 5	kita prod	table menu_sub
// record_type - 6	naujienos	table menu_sub
// record_type - 7	nuoma		table menu_sub

// record_id	- id iraso, kalbams - lt - lietuviu, en - anglu - ru - rusu

		if (record_type == "1" && (record_id != 'lt' && record_id != 'en' && record_id != 'ru'))
			return false;

		in_str_send = "record_type=" + record_type;
		in_str_send += "&id=" + record_id;

		implementAtiveX();
		resetResponse();
		g_xmlHTTP.open("POST", "record_get.php?", true);
  //g_xmlHTTP.setRequestHeader("Accept-Charset", "ISO-8859-1");
		g_xmlHTTP.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		g_xmlHTTP.setRequestHeader("Accept-Charset", "UTF-8");
//		g_xmlHTTP.onreadystatechange = readyStateChanged;
		g_xmlHTTP.send(in_str_send);
		g_xmlHTTP.onreadystatechange = function() { 
			if (g_xmlHTTP.readyState == 4 && g_xmlHTTP.status == 200)
				return_AtiveX(g_xmlHTTP.responseText);
		  } 

		return true;
  	}
 

function return_AtiveX(responseText)	{
//alert (responseText);

	if (responseText < 0)	return false;

		
		a_return = responseText.split('|');
		in_record_type = a_return[0];
		in_kalba = a_return[1];
		
//--- start kalbos	 - lentele	languages
		if (in_record_type == 1)	{
			if (existElement("id_language")) getElement("id_language").style.display = "block";

			if (existElement("id_kalba")) getElement("id_kalba").innerHTML = a_return[1];
			if (existElement("block_beg")) getElement("block_beg").value = a_return[2];
			if (existElement("block_end")) getElement("block_end").value = a_return[3];
			if (existElement("aktiv_beg")) getElement("aktiv_beg").value = a_return[4];
			if (existElement("aktiv_end")) getElement("aktiv_end").value = a_return[5];
			if (existElement("id_dateCreate")) getElement("id_dateCreate").innerHTML = a_return[6];
			if (existElement("id_dateEdit")) getElement("id_dateEdit").innerHTML = a_return[7];
			if (existElement("id_dateBlock")) getElement("id_dateBlock").innerHTML = a_return[8];
		
			return true;
		}
//--- end kalbos	 - lentele	languages


		return true;
}


function record_write(record_type, record_id, record_action)	{

g_record_type = record_type;
g_record_id   = record_id;

// record_type	- 1	kalbos	table languages
// record_id	- id iraso, kalbams - lt - lietuviu, en - anglu - ru - rusu
// record_action- insert, update

		if (record_type == "1" && (record_id != 'lt' && record_id != 'en' && record_id != 'ru'))
			return false;

		if (record_action != "insert" && record_action != 'update')
			return false;

document.menu_sub.submit();

		in_str_send = "record_type=" + record_type;
		in_str_send += "&id=" + record_id;
		in_str_send += "&action=" + record_action;
		in_str_send += "&id_menu=" + record_type;

		if (existElement("caption_lt")) in_str_send += "&caption_lt=" + getElement("caption_lt").value;
		if (existElement("apr_lt")) in_str_send += "&apr_lt=" + getElement("apr_lt").value;
		if (existElement("caption_en")) in_str_send += "&caption_en=" + getElement("caption_en").value;
		if (existElement("apr_en")) in_str_send += "&apr_en=" + getElement("apr_en").value;
		if (existElement("caption_ru")) in_str_send += "&caption_ru=" + getElement("caption_ru").value;
		if (existElement("apr_ru")) in_str_send += "&apr_ru=" + getElement("apr_ru").value;

		if (existElement("block_beg")) in_str_send += "&block_beg=" + getElement("block_beg").value;
		if (existElement("block_end")) in_str_send += "&block_end=" + getElement("block_end").value;
		if (existElement("aktiv_beg")) in_str_send += "&aktiv_beg=" + getElement("aktiv_beg").value;
		if (existElement("aktiv_end")) in_str_send += "&aktiv_end=" + getElement("aktiv_end").value;

		implementAtiveX();
		resetResponse();
		g_xmlHTTP.open("POST", "record_write.php?", true);
  //g_xmlHTTP.setRequestHeader("Accept-Charset", "ISO-8859-1");
		g_xmlHTTP.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		g_xmlHTTP.setRequestHeader("Accept-Charset", "UTF-8");
//		g_xmlHTTP.onreadystatechange = readyStateChanged;
		g_xmlHTTP.send(in_str_send);
		g_xmlHTTP.onreadystatechange = function() { 
			if (g_xmlHTTP.readyState == 4 && g_xmlHTTP.status == 200)
				return_AtiveX_write(g_xmlHTTP.responseText);
		  } 

		return true;
  	}
 

function return_AtiveX_write(responseText)	{
alert (responseText);

	if (responseText < 0)	return false;

// irasytas - neirasytas		
		a_return = responseText.split('|');
		in_record_type = a_return[0];
		in_kalba = a_return[1];
		

			return true;
		
//--- end kalbos	 - lentele	languages


		return true;
}


function record_add(record_type)	{

g_record_type = record_type;
g_record_id   = 0;
//alert(record_type);
// record_type - 1	kalbos		table languages
// record_type - 2	apie mus	table languages
// record_type - 3	kontaktai	table languages
// record_type - 4	svarstykles	table menu_sub
// record_type - 5	kita prod	table menu_sub
// record_type - 6	naujienos	table menu_sub
// record_type - 7	nuoma		table menu_sub

// record_id	- id iraso, kalbams - lt - lietuviu, en - anglu - ru - rusu

	if (existElement("id_language"))	getElement("id_language").style.display = "none";
	if (existElement("id_apie"))		getElement("id_apie").style.display = "none";
	if (existElement("id_kontaktai"))	getElement("id_kontaktai").style.display = "none";
	if (existElement("id_menu_sub_one")) getElement("id_menu_sub_one").style.display = "none";
	if (existElement("id_menu_sub"))	getElement("id_menu_sub").style.display = "none";
	if (existElement("id_naujiena"))	getElement("id_naujiena").style.display = "none";
	if (existElement("id_menu_main"))		getElement("id_menu_main").style.display = "none";
	if (existElement("id_menu_sub"))		getElement("id_menu_sub").style.display = "none";


	if (record_type == "1" && existElement("id_language"))	getElement("id_language").style.display = "block";
	if (record_type == "2" && existElement("id_apie"))		getElement("id_apie").style.display = "block";
	if (record_type == "3" && existElement("id_kontaktai"))	getElement("id_kontaktai").style.display = "block";

	if (record_type == "4" && existElement("id_menu_sub"))	{
		getElement("id_menu_sub").style.display = "block";
		if (existElement("id_menu_sub_one")) getElement("id_menu_sub_one").innerHTML = "Svarstyklės - nauja grupė";
	}

	if (record_type == "5" && existElement("id_menu_sub"))	getElement("id_menu_sub").style.display = "block";
	if (record_type == "6" && existElement("id_naujiena"))	getElement("id_naujiena").style.display = "block";
	if (record_type == "7" && existElement("id_menu_main"))		getElement("id_menu_main").style.display = "block";
	if (record_type == "8" && existElement("id_menu_sub"))		getElement("id_menu_sub").style.display = "block";

		return true;
  	}


function if_delete(record_type, record_id, record_caption)	{

//record_type		- type deleted (sub, prod, news)
//record_id			- id deleted
//record_caption	- caption deleted

	if (confirm("Panaikinti " + unescape(record_caption)))	{
		getElement("id_" + record_type).value=record_id;
		getElement("action_type").value="delete_" + record_type;
		getElement("menu").submit();
	}
}


//--- functions for advertisement ---------------

function set_dateTrust()	{

// set dateTrust and dateEnd in advertisement edit in admin

	if ($('#chk_publish').is(":checked"))	{
		var today = new Date();
		in_year = today.getFullYear();
		in_month = today.getMonth()+1;

		if (in_month.length == 1)
			in_month += '0';

		in_day = (today.getUTCDate() < 10) ? '0' + today.getUTCDate() : today.getUTCDate();
		in_time = today.toLocaleTimeString();

		$('#id_dateTrust_disabled').val(in_year+'-'+in_month+'-'+in_day+' '+in_time);
		$('#id_dateTrust').val(in_year+'-'+in_month+'-'+in_day+' '+in_time);

		in_month_end = in_month + 1;
		in_year_end = in_year;
		in_day_end = in_day;
		if (in_month_end > 12)	{
			in_month_end = '01';
			in_year_end++;
		}

		if (in_month_end == 02 && in_day > 28)	{
			in_month_end = '03';
			in_day_end = '01';
		}

		$('#id_dateEnd').val(in_year_end+'-'+in_month_end+'-'+in_day_end+' '+'23:59:59');
		$('#id_dateEnd_disabled').val($('#id_dateEnd').val());
		$('#id_dateEnd_disabled').attr("disabled","");
	} else {
		$('#id_dateTrust_disabled').val("");
		$('#id_dateTrust').val("");
		$('#id_dateEnd').val("");
		$('#id_dateEnd_disabled').val("");
		$('#id_dateEnd_disabled').attr("disabled","disabled");
	}

	set_status();
}

function set_dateBlock()	{

// set dateTrust and dateEnd in advertisement edit in admin

	if ($('#chk_block').is(":checked"))	{
		var today = new Date();
		in_year = today.getFullYear();
		in_month = today.getMonth()+1;

		if (in_month.length == 1)
			in_month += '0';

		in_day = (today.getUTCDate() < 10) ? '0' + today.getUTCDate() : today.getUTCDate();
		in_time = today.toLocaleTimeString();

		$('#id_dateBlock_disabled').val(in_year+'-'+in_month+'-'+in_day+' '+in_time);
		$('#id_dateBlock').val(in_year+'-'+in_month+'-'+in_day+' '+in_time);

		in_month_end = in_month + 1;
		in_year_end = in_year;
		in_day_end = in_day;
		if (in_month_end > 12)	{
			in_month_end = '01';
			in_year_end++;
		}

		if (in_month_end == 02 && in_day > 28)	{
			in_month_end = '03';
			in_day_end = '01';
		}

		$('#id_dateEnd_disabled').attr("disabled","disabled");

	} else {
		$('#id_dateBlock_disabled').val("");
		$('#id_dateBlock').val("");
		$('#id_dateEnd_disabled').attr("disabled","");
	}

	set_status();
}

function set_status()	{

// set status in advertisement edit in admin

		var today = new Date();
		in_year = today.getFullYear();
		in_month = today.getMonth()+1;

		if (in_month.length == 1)
			in_month += '0';

		in_day = today.getUTCDate();
		in_time = today.toLocaleTimeString();

		in_date_time = in_year + '-' + in_month + '-' + in_day + ' ' + in_time;


		$('#status').html("");
		if ($('#id_dateTrust').val().substr(0,4) <= 1970)
			$('#status').html('Neaktivuotas');					// 1 - neaktivuotas

		if ($('#id_dateBlock').val().substr(0,4) > '1970')
			$('#status').html('Blokuotas');						// 3 - blokuotas

		if ($('#id_dateEnd').val().substr(0,4) != '0000' && $('#id_dateEnd').val() < in_date_time)
			$('#status').html('Baigėsi galiojimo laikas');		// 4 - baigėsi galiojimo laikas

		if (!$('#status').html())
			$('#status').html('Aktivus');						// 2 - aktivus
}


function foto_delete_restore()	{

// toggle button panaikinti/atstatyti

	if ($('#foto_delete').val() == '0')	{
		$('#foto_delete').val('1');
		$('#btn_delete').val('Atstatyti');
		$('#foto_src').hide();
		$('#foto_file').hide();
	} else {
		$('#foto_delete').val('0');
		$('#btn_delete').val('Panaikinti');
		$('#foto_src').show();
		$('#foto_file').show();
	}

}

function advertisement_susidomėjau()	{

// send form to advertisement author

	if ($('#foto_delete').val() == '0')	{
		$('#foto_delete').val('1');
		$('#btn_delete').val('Atstatyti');
		$('#foto_src').hide();
		$('#foto_file').hide();
	} else {
		$('#foto_delete').val('0');
		$('#btn_delete').val('Panaikinti');
		$('#foto_src').show();
		$('#foto_file').show();
	}

}

//--- /functions for advertisement ---------------


function get_content(get_what, get_id)	{
// get_what	-	show_sub
//				show_prod
//				show_one
//				send_email
//				show_kontaktai
//				create_mail
//				show_news	(6,7,8)
//				show_apie	about
//				show_services
//				show_partners
//				search/value

//alert(get_what);

//alert(getElement("menu_sub_" + get_id).bgcolor);
	
		if (get_what.indexOf('svarstykles') != -1 || get_what.indexOf('scales') != -1)	{
			$('#id_svarstykles_submenu').show();
			$('#id_advertisement_submenu').hide();
			$('#id_kita_produkcija').hide();
		}

		if (get_what.indexOf('kita-produkcija') != -1 || get_what.indexOf('other-production') != -1)	{
			$('#id_svarstykles_submenu').hide();
			$('#id_advertisement_submenu').hide();
			$('#id_kita_produkcija').show();
		}
		
		if (get_what.indexOf('skelbimu-lenta') != -1 || get_what.indexOf('advertisement') != -1)	{
			$('#id_svarstykles_submenu').hide();
			$('#id_kita_produkcija').hide();
			$('#id_advertisement_submenu').show();

			if (get_what == 'skelbimu-lenta' || get_what == 'advertisement')
				return;
		}
		
		if (get_what.indexOf('search/') != -1)	{
			a_get_what = get_what.split('/');
			get_what = a_get_what[0];
			get_id	 = a_get_what[1];
		}

		
//		if (existElement(last_menu_sub_a)) getElement(last_menu_sub_a).style.display = "none";
//		if (existElement(last_menu_sub)) getElement(last_menu_sub).style.display = "";

//		if (existElement("menu_sub_a_" + get_id)) getElement("menu_sub_a_" + get_id).style.display = "";
//		if (existElement("menu_sub_" + get_id)) getElement("menu_sub_" + get_id).style.display = "none";

//		last_menu_sub_a = "menu_sub_a_" + get_id;
//		last_menu_sub   = "menu_sub_" + get_id;

//		if (existElement("menu_sub_" + get_id)) getElement("menu_sub_" + get_id).font-size = "15px";

//alert(getElement("menu_sub_" + get_id).bgcolor);

//  alert(getElement("menu_sub_" + get_id).class.value);

		in_str_send = "lng=" + "lt";
		in_str_send += "&get_what=" + get_what;
		in_str_send += "&get_id=" + get_id;

	if (get_what == 'del_advertisement')	{

		if (!confirm("Panaikinti skelbimą?"))
			return false;
	}

	if (get_what == 'send_email_question')	{
		$(".error").remove();
		if (check_form_question() == false)
			return false;

		in_str_send += "&imone="	+ encodeURIComponent(getElement("imone").value);
		in_str_send += "&vardas="	+ encodeURIComponent(getElement("vardas").value);
		in_str_send += "&email="	+ encodeURIComponent(getElement("email").value);
		in_str_send += "&tel="		+ encodeURIComponent(getElement("tel").value);
		in_str_send += "&klausimas=" + encodeURIComponent(getElement("klausimas").value);
	}

	if (get_what == 'advertisement_message_send')	{
		$(".error").remove();
		if (check_form_message_send() == false)
			return false;

		in_str_send += "&type="		+ $("#type").val();
		in_str_send += "&corr_number="	+ encodeURIComponent($("#corr_number").val());
		in_str_send += "&imone="	+ encodeURIComponent($("#imone").val());
		in_str_send += "&vardas="	+ encodeURIComponent($("#vardas").val());
		in_str_send += "&email="	+ $("#email").val();
		in_str_send += "&tel="		+ encodeURIComponent($("#tel").val());
		in_str_send += "&tekstas="	+ encodeURIComponent($("#tekstas").val());
		in_str_send += "&chk_contact="	+ (0 + $("#chk_contact").attr('checked'));
	}

	if (get_what == 'write_advertisement')	{
		$(".error").remove();
		if (check_form_advertisement() == false)
			return false;


var options = {
	  url: "action.php",
	  type: "POST",
		  success: function(data) {
//			  alert(data);
				if (data)	{
					$("#id_caption_center").html($('#span_caption_hidden').html());
					document.title = $("#id_caption_center").html();
					$('#id_front').html(data);
				}
				  }
			};

 
	$("#frmSend").ajaxSubmit(options);

	} else {
		$('#id_front').load('action.php', in_str_send, function(){
														$("#id_caption_center").html($('#span_caption_hidden').html());
														document.title = $("#id_caption_center").html();

//--- bind click for tag a -------------------------

$("#id_front a:not([rel='noindex'])").bind("click",function(){

			var hash = this.href;

			in_hash = hash.replace(g_protocol_host, '');
			if (in_hash != '')
				if (in_hash.indexOf('/') == 0)
					hash = hash.replace(g_protocol_host, '');

			$.historyLoad(hash);

			return false;
			});

//--- /bind click for tag a -------------------------
															});
	}

		return true;
}


//--- functions from http://www.mikage.to/jquery/jquery_history.html
//--- form plugin jquery.history.js (Last Update: 2009/10/14)

	// PageLoad function
	// This function is called when:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser
	function pageload(hash) {
//		 alert("pageload: " + hash);
		// hash doesn't contain the first # character.
		if(hash) {
			// restore ajax loaded state
			if($.browser.msie) {
				// jquery's $.load() function does't work when hash include special characters like aao.
				hash = encodeURIComponent(hash);
				hash = hash.replace(/%2F/g, '/');				// replace %2F -> / in hash
			}
//			$("#id_front").load(hash + ".html");

			get_content(hash.replace('/', ''),'');
			
/*
			if (hash == '/apie-mus' || hash == '/about-us')	{
				get_content("about", "");
				$("#id_caption_center").html("Apie");
			}

			if (hash == '/kontaktai' || hash == '/contacts')	{
				get_content("show_kontaktai", "");
				$("#id_caption_center").html("Kontaktai");
			}

			if (hash == '/svarstykles' || hash == '/scales')	{
				get_content("show_sub", "4");
				$("#id_caption_center").html("Kontaktai");
			}
*/
		} else {
			// start page
			get_content("akcijos", "");
		}
	}

	
	$(document).ready(function(){
		// Initialize history plugin.
		// The callback is called at once by present location.hash. 
		$.historyInit(pageload, '');
		
		// set onlick event for buttons
		$("a[rel!='index']").click(function(){
			// 
			var hash = this.href;

//			hash = hash.replace(/^.*#/, '');

//			hash = hash.replace(/^.*#/, '/');

			in_hash = hash.replace(g_protocol_host, '');
			if (in_hash != '')
				if (in_hash.indexOf('/') == 0)
					hash = hash.replace(g_protocol_host, '');

//			alert("historyInit: " + hash);

			// moves to a new page. 
			// pageload is called at once. 
			// hash don't contain "#", "?"
			$.historyLoad(hash);
//alert('ready: '+this.href)
//			get_content(this.href.replace(g_protocol_host+'/', ''), "");

			return false;
		});

		$("select[rel!='index']").change(function(){
			// 
			var hash = "/search/" + this.value;

//			hash = hash.replace(/^.*#/, '');

//			hash = hash.replace(/^.*#/, '/');

			in_hash = hash.replace(g_protocol_host, '');
			if (in_hash != '')
				if (in_hash.indexOf('/') == 0)
					hash = hash.replace(g_protocol_host, '');

//			alert("historyInit: " + hash);

			// moves to a new page. 
			// pageload is called at once. 
			// hash don't contain "#", "?"
			$.historyLoad(hash);
//alert('ready: '+this.href)
//			get_content(this.href.replace(g_protocol_host+'/', ''), "");

			return false;
		});
	});

//----
