// autocomplete fields
$.fn.completeMe = function() {
	$(this).each(function(){
		$(this).focus(function(){
			if(this.value == this.defaultValue){
				this.value = '';
				if(this.innerHTML)
					this.innerHTML = '';
			}
		});
		
		$(this).blur(function(){
			if(this.value == ''){
				this.value = this.defaultValue;
				if(this.innerHTML)
					this.innerHTML = this.defaultValue;
			}
		});
	});
}

// force ajax on the forms - only for fancybox forms!!!
$.fn.ajaxMe = function() {
	$(this).each(function() {
		$(this).bind("submit", function() {
			$.fancybox.showActivity();

			$.ajax({
				type		: "POST",
				cache	: false,
				url		: $(this).attr('action'),
				data		: $(this).serializeArray(),
				success: function(data) {
					$.fancybox(data);
				}
			});
			
			return false;
		});
	});
}

// force ajax on the forms - only for fancybox forms (LIVE edition) !!!
function ajaxMe() {
	$('form.ajaxMe').live('submit', function() {
		$.fancybox.showActivity();

		$.ajax({
			type		: "POST",
			cache	: false,
			url		: $(this).attr('action'),
			data		: $(this).serializeArray(),
			success: function(data) {
				$.fancybox(
					data,
					{
        		'transitionIn'	:	'elastic',
						'transitionOut'	:	'elastic',
						'padding'				: 0,
						'width'					: 660,
						'height'				: 450,
						'overlayColor'	: '#000000'
					}
				);
			}
		});
		
		return false;
	});
}

// printer friendly
$.fn.printerFriendly = function() {
	var urlToOpen = $(location).attr('href') + '?printPage=1';
	var x = (screen.width-800)/2, y = (screen.height-600)/2;
	$(this).each(function() {
		$(this).bind("click", function() {
			window.open(urlToOpen, "CtrlWindow", "width=800,height=600,toolbar=no,menubar=yes,location=no,scrollbars=yes,resizable=no, screenX="+x+", screenY="+y+", left="+x+", top="+y);
			return false;
		});
	});
}

// timed page reload
$.fn.reloadPage = function(timerS) {
	if (!timerS) timerS = 1; //defaults to imediate
	setTimeout(function() {
		location.reload();
	}, timerS);
}

// force target="_blank" on links with class name "target_blank"
$.fn.setupTargetBlank = function() {
	
	$(this).each(function() {
		$(this).bind("click", function() {
			if($(this).attr('href') != '#')
				window.open(this.href);
      return false;
		});
	});
	
}

// force target="_blank" on links with class name "target_blank" (LIVE edition)
function setupTargetBlank() {
	$('a.target_blank').live('click', function() {
		if($(this).attr('href') != '#')
			window.open(this.href);
    return false;
	});
}

// force ajax on the first click on the share links
$.fn.setupShareLinks = function() {
	var baseHref = $('base').attr('href');
	var ajaxTo = baseHref + 'index.html' + '/mainpage|getShortUrl';
	
	$(this).each(function() {
		$(this).bind("click", function() {
			// show activity
			var prevHref = $(this).attr('href');
			var icon = $(this).children(':first');
			icon.attr('orig-src', icon.attr('src'));
			icon.attr('src', 'images/icons/loading.gif');
			
			$.ajax({
				type		: "POST",
				cache	: false,
				url		: ajaxTo,
				data		: { url: $(location).attr('href') },
				success: function(data) {
					// short url generation is a success
					$('.shareLink').each(function() {
						$(this).attr('href', this.href + data);
						$(this).unbind('click');
						$(this).removeClass('shareLink');
						$(this).addClass('target_blank');
					});
					icon.attr('src', icon.attr('orig-src'));
					$('.shareLink').removeAttr('orig-src');
					window.open(prevHref + data);
				}
			});
			
			return false;
		});
	});
}

// show tooltip with ajax data
function tooltipMe(tooltipClass) {

	$('a.'+tooltipClass).each(function(){
		$(this).qtip({
			content: {
				text: '<img class="throbber" src="images/icons/loading.gif" alt="Se incarca..." />',
				ajax: {
					url: $(this).attr('href') // Use the href attribute of each element for the url to load
				},
				title: {
					text: $(this).attr('title'), // Give the tooltip a title using each elements title
					button: true
				}
			},
			position: {
				at: 'top center', 
				my: 'bottom center',
				adjust: { screen: true }
			},
			show: {
				event: 'click',
				solo: true
			},
			hide: 'unfocus',
			style: {
				classes: 'ui-tooltip-wiki ui-tooltip-light ui-tooltip-shadow'
			}
		})
		// Make sure it doesn't follow the link when we click it
    .click(function() { return false; });
	});
	
}

// show unintrusive browser deprecated warning
function ieDeprecated(ver, msg) {
	if (!ver) ver = 6; //default warns on ie 6 and lower
	if (!msg) msg = 'Your browser is deprecated. &nbsp; Please update to latest version to enjoy the full web experience!'; //default message

	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
		var ieversion = new Number(RegExp.$1); // capture x.x portion and store as a number
		if (ieversion <= ver) {
			$.jnotify(msg, true);
		}
	}
};

// custom pagination
function setPage(pageID, hInput, formID) {
	$('#' + hInput).val(pageID);
	// $('#' + formID).submit();
	setupSmartFilters(formID);
}

// fill placeholders with google maps
$.fn.launchGmaps = function() {
	
	$(this).each(function() {

		// [try to] get (JSON) data from "rel" attribute
		var inlineData = $(this).attr('rel'), data = {};
		try {
			data = jQuery.parseJSON(inlineData.replace("&quot;", '"'));
		}
		catch(e) {} //console.log('error', e);};

		// replace P with DIV
		var self = $('<div>')
			.addClass($(this).attr('class'))
			.insertAfter($(this));
		
		if (!data.gps || !String(data.gps).length) {
			if ($(this).attr('data-gps')) {
				data.gps = $(this).attr('data-gps');
			}
			else {
				try {
					data.gps = $.trim($(this).html());
				} catch (e) {};
			}
		}
		$(this).remove();
		self.data('_data', data);

		// setup gmap
		$(self)
			.gmap({
				'center': $(self).data('_data').gps, 
				'zoom': 15 })
			.bind(
				'init', 
				function(ev, map) {
					$(self)
						.gmap(
							'addMarker', 
							{ 'position': $(self).data('_data').gps })
						.click(function() {
							$(self).gmap('openInfoWindow', { 'content': '' }, this);
						});
				});
	});
	
}

// load comments dinamically
function loadComments(ajaxTo, objectName, objectID){
	$('#commentsContainer').html('<img src="images/icons/loading.gif" border="0" align="center"/>');
	
	$.post(
		ajaxTo,
		{'objectName' : objectName, 'objectID': objectID},
		function(data){
			$('#commentsContainer').html(data);
		}
	);
}

// focus on first input in the document or the first input with class [focusMe]
function focusMe() {
	// focus first input havind the css class "focusMe" or the first input text found
	if($('input.focusMe:first').length) {
		$('input.focusMe:first').focus();
	} else {
		$('input[type=text]:first').focus();
	}
	// submit form on enter for all text inputs & password inputs
	$('input[type=text]').keypress(function(e){
		if(e.which == 13 && $(this).hasClass('triggerFancy')){
			e.preventDefault();
			$(this).next('a').trigger('click');
		} else if(e.which == 13) {
			e.preventDefault();
			$(this).parents('form:first').submit();
		}
	});
	$('input[type=password]').keypress(function(e){
		if(e.which == 13){
			e.preventDefault();
			$(this).parents('form:first').submit();
		}
	});
}

// what to do when DOM fully loaded
$(document).ready(function(){
	
	$('.completeMe').completeMe();
	
	// $('form.ajaxMe').ajaxMe();
	ajaxMe(); focusMe();
	
	// fancy box initialization
	$(".fancyb").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'padding'				: 0,
		'width'					: 660,
		'height'				: 450,
		'overlayColor'	: '#000000'
	});
	
	// custom fancybox with callbacks for the recatpcha forms
	$(".fancybFrame").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'padding'				: 0,
		'width'					: 660,
		'height'				: 450,
		'showCloseButton': false,
		'overlayColor'	: '#000000',
		'type' 					: 'iframe',
		'onComplete'		: function(){
			$('#fancybox-frame').load(function() {
				var currHeight = $(this).contents().find('body').height();
				$('#fancybox-content').css({"height":currHeight});
				$.fancybox.resize();
			});
		}
	});
	
	// XHTML 1.1 compliant target blank replacement
	// $('a.target_blank').setupTargetBlank();
	setupTargetBlank();
	
	// short url generation
	$('.shareLink').setupShareLinks();
	
	// print page buttons prep
	$('.printPage').printerFriendly();
	
	// google maps launcher
	$('.gmap').launchGmaps();
	
	// video js
	if(typeof VideoJS != 'undefined')
		VideoJS.setupAllWhenReady();
	
	// parallax
	$('#parallax .parallax-layer').parallax({
    mouseport: $("#header"),
		decay: 0.9
	});
	$('#parallax2 .parallax-layer').parallax({
    mouseport: $("#jos"),
		decay: 0.9
	});
	
	// ie browser deprecation notice
	ieDeprecated();
	
});
var RecaptchaOptions = { theme : 'blackglass' };

