//onerror = handleErr;

function handleErr(msg, url, l) {
	
	txt  = "There was an error on this page.\n\n";
	txt += "Error: " + msg + "\n";
	txt += "URL: " + url + "\n";
	txt += "Line: " + l + "\n\n";
	txt += "Click OK to continue.\n\n";
	alert(txt);
	return true;
	
}// END handleErr


function redirect(url) {
	
 	window.location.href = url;
				
}// END redirect


function openPage(path, title, width, height, type) {
	
	window.open(path, title, 'width=' + width + ',height=' + height + ',toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes');
	return false;
	
}// END openPage


function fns_getElementById(element_id) {
	
	var obj = null;
	if (document.all) {
		obj = document.all[element_id];
	}else if (document.getElementById) {
		obj = document.getElementById(element_id);
	}
	return obj;
	
}// END fns_getElementById
 
 
function fns_getObjElementById(el_obj, element_id) {
	
	var obj = null;
	if (el_obj.all) {
		obj = el_obj.all[element_id];
	}else if (el_obj.getElementById) {
		obj = el_obj.getElementById(element_id);
	}
	return obj;
	
}// END fns_getObjElementById


function DraugiemSay(title, url, titlePrefix) {
	
	window.open(
		'http://www.draugiem.lv/say/ext/add.php?title=' + encodeURIComponent( title ) +
		'&link=' + encodeURIComponent( url ) +
		( titlePrefix ? '&titlePrefix=' + encodeURIComponent( titlePrefix ) : '' ),
		'',
		'location=1,status=1,scrollbars=0,resizable=0,width=530,height=400'
		);
	return false;
	
}// END DraugiemSay

// tabi
$.fn.tabs = function(options) {
	var opts = $.extend({}, $.fn.tabs.defaults, options);
	return this.each(function(i) {
		var $this = $(this);
		$this.attr('id', 'id_gl_tabs_' + (i + 1));
		$btns = $this.find('.btns a').click(function(e) {
				$.fn.tabs.showTab($(this));
				e.preventDefault();
				return false;
			});
		$btns.each(function() {
			if ($(this).parent().attr('class') == 'active') $.fn.tabs.showTab($(this));
		});
	});
};

$.fn.tabs.defaults = {};

$.fn.tabs.showTab = function($btn) {
	$cont = $btn.parent().parent().parent().parent().find('.cont');
	$btn.parent().parent().find('li').removeClass('active');
	$btn.parent().addClass('active');
	var tab_id = $cont.parent().attr('id');
	var href = $btn.attr('href');
	$tabs = $cont.find('.tab').css('display', 'none');
	if (href[0] == '#') {
		$btn.parent().parent().parent().parent().find(href).css('display', 'block');
	}else {
		var tmp = href.split('?');
		var link = tmp[0];
		var data = tmp[1];
		var html = $.ajax({
			type: 'GET',
			url: link,
			data: data,
			dataType: 'html',
			success: function(html){
				$cont = $('#' + tab_id + ' .cont');
				$tabs = $('#' + tab_id + ' .cont .tab');
				var founded = false;
				$tabs.each(function() {
						if ($(this).attr('id') == '') {$(this).html(html); $(this).css('display', 'block'); founded = true;}
					});
				if (founded == false) {
					var fhtml = $cont.html();
					fhtml += '<div class="tab" style="display:block;">' + html + '</div>';
					$cont.html(fhtml);
				}
			}
		});
	}
};

// fontu palielināšana
$.fn.fontSizeBtns = function() {
	return this.each(function() {
		var $cont = $(this);
		$('a.fl_sm').click(function(e) {
				e.preventDefault();
				var fs = parseFloat($cont.css('font-size'), 10) - 1;
				if (fs >= 10) $cont.css('font-size', fs + 'px');
			});
		$('a.fl_lg').click(function(e) {
				e.preventDefault();
				var fs = parseFloat($cont.css('font-size'), 10) + 1;
				if (fs <= 16) $cont.css('font-size', fs + 'px');
			});
	});
};

// important_lines
$.fn.blImportantLines = function(options) {
	var opts = $.extend({}, $.fn.blImportantLines.defaults, options);
	return this.each(function() {
		var tmp = $(this).find('.nav span').html().split('/');
		opts.active_item = parseInt(tmp[0], 10);
		opts.items = parseInt(tmp[1], 10);
		$(this).find('.nav a').click(function(e) {
				e.preventDefault();
				var n_item = opts.active_item;
				if ($(this).attr('class') == 'l') {n_item--; if(n_item < 1) n_item = opts.items;}
				else {n_item++; if(n_item > opts.items) n_item = 1;}
				opts.active_item = n_item;
				$.fn.blImportantLines.showItem($(this).parent().parent(), opts, false);
			}).mouseover(function(){
				var $img = $(this).find('img');
				if ($(this).attr('class') == 'l') $img.attr('src', HTTP_ROOT + '_main/img/important_lines_btn_l_on.gif');
				else $img.attr('src', HTTP_ROOT + '_main/img/important_lines_btn_r_on.gif');
			}).mouseout(function(){
				var $img = $(this).find('img');
				if ($(this).attr('class') == 'l') $img.attr('src', HTTP_ROOT + '_main/img/important_lines_btn_l.gif');
				else $img.attr('src', HTTP_ROOT + '_main/img/important_lines_btn_r.gif');
			});
		
		opts.t = false;
		$(this).mouseover(function() {
				clearTimeout(opts.t);
			}).mouseout(function() {
				var $obj = $(this);
				opts.t = setTimeout(function() {opts.active_item++; $.fn.blImportantLines.showItem($obj, opts, true);}, opts.timer);
			});
		$.fn.blImportantLines.showItem($(this), opts, true);
	});
};

$.fn.blImportantLines.defaults = {timer:3000};

$.fn.blImportantLines.showItem = function($obj, opts, start_timer) {
	if(opts.active_item > opts.items) opts.active_item = 1;
	$obj.find('.nav span').html(opts.active_item + '/' + opts.items);
	$obj.find('.item.active').removeClass('active');
	$item = $obj.find('.item:eq(' + (opts.active_item - 1) + ')');
	$item.addClass('active');
	if (start_timer == true) {
		opts.t = setTimeout(function() {opts.active_item++; $.fn.blImportantLines.showItem($obj, opts, true);}, opts.timer);
	}
};


var text2xml = function(s) {
	var x, ie = /msie/i.test(navigator.userAgent);
	try{
		var p = ie? new ActiveXObject("Microsoft.XMLDOM") : new DOMParser();
		p.async = false;
	}catch(e){ throw new Error("XML Parser could not be instantiated") };
	try{
		if(ie) x = p.loadXML(s)? p : false;
		else x = p.parseFromString(s, "text/xml");
	}catch(e){ throw new Error("Error parsing XML string") };
	return x;
};


$.fn.makeExternalLinks = function() {
	return this.each(function() {
		$(this).click(function() {
				window.open(this.href);
				return false;
			});
	});
}; // END makeExternalLinks


$.fn.mainNav = function(options) {
	var opts = $.extend({}, $.fn.mainNav.defaults, options);
	return this.each(function() {  
		var $this = $(this);
		$this.find('li a').mouseover(function() {
				if (opts.ondiv || opts.onlink) {
					return false;
				}
				if (opts.timeoutID > 0) {
					clearTimeout(opts.timeoutID);
				}
				opts.onlink = true;
				$.fn.mainNav.initTooltip($this, opts, $(this));
	 		}).mouseout(function(){
	 			opts.onlink = false;
	 			opts.timeoutID = setTimeout(function() {
	 					$.fn.mainNav.hideTooltip($this, opts)
	 				}, 300);
	 		});
	 	
	 	$('#nav_popup').mouseenter(function() {
	    		opts.ondiv = true;
	    	}).mouseleave(function() {
			    opts.ondiv = false;
			    $.fn.mainNav.hideTooltip($this, opts)
			});
	 	
	});
};

$.fn.mainNav.defaults = {request:null, onlink:false, ondiv:false, bubbleExists:false, timeoutID:0};

$.fn.mainNav.initTooltip = function($obj, opts, $item) {
	
	if ($item.parent().hasClass('active') != true) {
		
		var cat = $item.attr('rel');
		opts.request = $.ajax({
	            url: HTTP_ROOT + '_main/zinas/get_nav_block.ajax.php',
	            type: "POST",
	            data: 'cat=' + cat + '',
	            complete: function(req) {
	                if (req.status == 200) { //success
	                	var txt = req.responseText.split('|');
	                	if (txt[0] != 'err') {
	                		opts.bubbleExists = true;
	                        $.fn.mainNav.createTooltip($obj, opts, $item, req.responseText);
		                }else {
		                	$.fn.mainNav.hideTooltip($obj, opts);
		                }
	                }else {
	                	$.fn.mainNav.hideTooltip($obj, opts);
	                }
	            }
	        });
		
	}
	
};

$.fn.mainNav.createTooltip = function($obj, opts, $item, html) {
	var pos = $item.position();
	var tPosX = pos.left - 1;
	var tPosY = pos.top + $item.height() + 2;
	$('#nav_popup').html(html).css({'top':tPosY + 'px', 'left':tPosX + 'px', 'display':'block'});
};

$.fn.mainNav.hideTooltip = function($obj, opts) {
	clearTimeout(opts.timeoutID);
	if (opts.bubbleExists && !opts.ondiv) {
		opts.bubbleExists = false;
		opts.request.abort();
		$('#nav_popup').css('display', 'none');
	}
};



/*****************************************/
// parvertibasIntroBlock
/*****************************************/
$.fn.parvertibasIntroBlock = function(options) {
	var opts = $.extend({}, $.fn.parvertibasIntroBlock.defaults, options);
	return this.each(function() {  
		$.fn.parvertibasIntroBlock.init($(this));
	});
};

$.fn.parvertibasIntroBlock.defaults = {};

$.fn.parvertibasIntroBlock.init = function($obj) {
	
	$obj_cont = $obj.find('.cont');
	
	// Navigacijas pogas
	$obj.find('div.nav a.btn').click(function(e) {
			e.preventDefault();
			var nr = parseInt($(this).attr('href').split('#')[1], 10);
			
			$obj_cont.fadeTo(100, 0.2, function() {
					$.ajax({
							url: HTTP_ROOT + 'maja/parvertibas/intro_block.ajax.php',
							type: "POST",
							data: 'nr=' + nr,
							complete: function(req) {
								if (req.status == 200) { //success
									$obj.find('.cont').html(req.responseText);
									$.fn.parvertibasIntroBlock.init($obj);
									$obj_cont.fadeTo(100, 1);
								}else {}
							}
						});
				});
			
		});
	
}// END init


/*****************************************/
// velesanas2010voteBlock
/*****************************************/
$.fn.velesanas2010voteBlock = function(options) {
	var opts = $.extend({}, $.fn.velesanas2010voteBlock.defaults, options);
	return this.each(function() {  
		$.fn.velesanas2010voteBlock.init(opts, $(this));
	});
};

$.fn.velesanas2010voteBlock.defaults = {blhref: HTTP_ROOT + 'temas/templates/velesanas-2010/bl_vote/', votehref: HTTP_ROOT + '_plugins/polls/vote.ajax.php'};

$.fn.velesanas2010voteBlock.init = function(opts, $obj) {
	
	$.ajax({
			url: opts.blhref + 'display.ajax.php',
			type: 'GET',
			data: '',
			complete: function(req) {
				if (req.status == 200) { //success
					$obj.html(req.responseText);
					$obj.find('input.btn').click(function() {
							$.fn.velesanas2010voteBlock.vote(opts, $obj);
						});
				}else {}
			}
		});
	
}// END init

$.fn.velesanas2010voteBlock.vote = function(opts, $obj) {
	
	var answer = $obj.find('select').val();
	if (answer != 0) {
		
	    $obj.fadeTo(300, 0.3, function() {
	    	$obj.find('input.btn').attr('value', '...').attr('disabled', 'disabled');
	        $.ajax({
	            url: opts.blhref + 'vote.ajax.php',
	            type: 'POST',
	            data: 'answer=' + answer + '',
	            complete: function(req) {
	                if (req.status == 200) { //success
	                	var txt = req.responseText.split('|');
	                	if (txt[0] == 'err' && txt[1] == 2) alert('Tu jau esi nobalsojis!' + "\n" + 'Balsot var vienu reizi 24 stundās.');
	                	if (txt[0] == 'err' && txt[1] != 2) {
	                		alert('Kļūda! Lūdzu pārlādējiet lapu un mēģiniet vēlreiz!');
	                	}else {
	                		if (txt[0] == 'ok') alert('Balsojums pieņemts!');
	                		$.fn.velesanas2010voteBlock.init(opts, $obj);
	                		$obj.fadeTo(100, 1);
	                	}
	                }else {}
	            }
	        });
	    });
	   	
	}else alert('Nav izvēlēts variants!');
	
}// END vote



$(document).ready(function() {
	
	$('.tabs').tabs();
	$('.fl_bloks').fontSizeBtns();
	$('#bl_important_lines').blImportantLines();
	
	// Popup banner
	if ($("#ads_popup_ad").length > 0) $.fn.colorbox({width:600, inline:true, href:'#ads_popup_ad', open:true, title:'Reklāma', overlayClose:true});
	
	$('a[rel*=external]').makeExternalLinks();
	$('.plugin_polls_poll').pluginPolls({bar_max_width:250});
	
	// Menu
	$('#nav').mainNav();
	
	// Pārvērtību bloks
	$('#id_parvertibas_intro_block').parvertibasIntroBlock();
	
	// Saeimas 2010 balsošanas bloks
	$('#topic_velesanas_2010_vote').velesanas2010voteBlock();
	
});
