/* 
 * jsEffects JavaScriptUtils module
 * 
 * Provides visual effects and usability-related improvements.
 * 
 * version 08-08-11
 *
 */


// Element centering
jQuery.fn.centerScreen = function() {
	return this.each(function(){
	    var obj = $(this);
	    obj.css('top', $(document).scrollTop() + $(window).height()/2-obj.outerHeight()/2);
	    obj.css('left', $(window).width()/2-obj.outerWidth()/2);
		obj.css('position', 'absolute');
	});
};
jQuery.fn.centerH = function() {
	return this.each(function(){
	    var obj = $(this);
	    obj.css('left', $("body").width()/2-obj.outerWidth()/2);
		obj.css('position', 'absolute');
	});
};




var basePath = "";
var basePathFull = "";
var i, scripts = document.getElementsByTagName("script");
for (i = 0; i < scripts.length; i++) {
	if (scripts[i].src.match("jquery.js")) { 
		basePath = scripts[i].src.replace("/js/jquery.js", "");
		basePathFull = scripts[i].src.replace("/js/jquery.js", "%%%URL%%%");
		break;
	}
}

function url(url) {
	// Absolute path
	if (url.substring(1,0) == "/") {
		return basePathFull.replace("%%%URL%%%", url);
	} else {
		return url;
	}
}

// Import libraries
function $import(path) {
    document.write("<" + "script src=\"" + url("/js/" + path) + "\"></" + "script>");
}

$import("jsextensions.js");
$import("jsplugins.js");


/* 
 * Functions implementation
 */

// Adds code and class to make floating element on top over selects in ie
jQuery.fn.selectFree = function() {
	return this.each(function(){
		//var content = $(this).html();
		$(this).append('<!--[if lte IE 6.5]><iframe></iframe><![endif]-->');
        $(this).addClass("select-free");
	});
}

/* Function for positioning popup frames according to another element (refElem) and alignMode */
jQuery.fn.sameOffset = function(refElem, alignMode) {

	var offset = refElem.offset({ border: true, padding: true });

	var left = offset.left;
	var top = offset.top;
	
	var absTopFix = 0;
	var absLeftFix = 0;
	var offset;
	refElem.parents().each(function(){
		if ($(this).css('position') == 'absolute') {				
			offset = $(this).offset({ border: true, padding: true });
			absTopFix += offset.top;
			absLeftFix += offset.left;
		}
	});

	if (alignMode == 'bottom') top += refElem.outerHeight();	
	else if (alignMode == 'right') left += refElem.outerWidth();
		
	this.css({'position': 'absolute', 'left': left, 'top': top });
	return this;
	
}


// Is Child plugin
jQuery.fn.isChild = function(test) {
	s = this.get(0);
	d = $(test).get(0);
	while(s) {
		if (s == d) return true;
		s = s.parentNode;
	}
	return false;
}


// addHoverAbility function
jQuery.fn.addHoverAbility = function() {
	return this.each(function(){
		$(this).hover(
			function () { $(this).addClass('hover'); },
			function () { $(this).removeClass('hover'); }
		);
	});
}


// Attach function to click and enter-invoked keypress
jQuery.fn.attachSafeClick = function(regFunc) {
	return this.each(function(){
		$(this).click(regFunc).keypress( function(e) {
			if (e.which == 13) $(this).click(e);	
		} ).filter("a").data('modifiedLink', true);
	});
}


// Returns class parameter (paramname-paramvalue),
// if not available, returns null
jQuery.fn.getClassParam = function(name) {
	var className = this.attr('class') + ' ';
	if (className && (className.indexOf(name) > -1)) {
		var startIndex = className.indexOf(name);
		return className.substring(startIndex + name.length+1, className.indexOf(" ", startIndex + 1));
	} else {
		return null;
	}
}


// Glues an element to the bottom of a page (used for footers)
jQuery.fn.glueBottom = function() {
	var elem = $(this);
	function glueBottomProc() {
		if (($(window).height() - elem.outerHeight()) > $('body').height()) {		
			elem.css({
				position: 'absolute',
				top: ($(window).height() - elem.outerHeight()),
				left: 0});	
		} else {
			elem.css({
				position: '',
				top: 0,
				left: 0});		
		}
	}
	glueBottomProc();
	setInterval(glueBottomProc, 100); /* Refresh element position every 250 ms */
}








// Popups a window with parameters
function openPopupWindow(url, title, x, y, width, height) {
	var features = "scrollbars=1, location=0, left="+x+", top="+y+", statusbar=0, menubar=0, width="+width+", height="+height;
	var theWindow = window.open(url, title, features);
	theWindow.focus();
	theWindow.moveTo(x, y);
	return theWindow;
}






/* Popup layer management */
var popupLayerElement = null;
var popupLayerElementTarget;
function closeLastPopupLayerElement() {
	if (popupLayerElement != null) { // Some popupLayer is registered, close it
		if (popupLayerElement.closePopup) {
			// Call popup layer destructor if available
			popupLayerElement.closePopup();
		} else
			popupLayerElement.hide();
		popupLayerElement = null;
	}
}
jQuery.fn.makePopup = function(refElem) {
	if ((this != popupLayerElement) && popupLayerElement && !this.isChild(popupLayerElement)) closeLastPopupLayerElement();
	popupLayerElement = this;
	popupLayerElementTarget = refElem;
	this.sameOffset(popupLayerElementTarget, 'bottom').show();
	return this;
}




/* Form layer management
   Form layer is closed when an input element loses focus,
   is clicked somewhere outside on the layer active region on page
   and is restricted to show only one component at one time. */
var formLayerElement = null;
var formLayerElementTarget;
function closeLastFormLayerElement() {
	if (formLayerElement != null) { // Some formLayer is registered, close it
		if (formLayerElement.closePopup) {
			// Call popup layer destructor if available
			formLayerElement.closePopup();
		} else
			formLayerElement.hide();
		formLayerElement = null;
	}
}
jQuery.fn.makeForm = function(refElem) {
	if ((this != formLayerElement) && formLayerElement && !this.isChild(formLayerElement)) closeLastFormLayerElement();
	formLayerElement = this;
	formLayerElementTarget = refElem;
	this.sameOffset(formLayerElementTarget, 'bottom').show();
	return this;
}











/* Hover layer management */
var hoverLayerElement = null;
var hoverLayerElementTarget;

// Create container for hover elements
var hoverLayerElementsContainer = $(document.createElement('div')).attr('id', 'hoverLayerElementsContainer');
$(document).ready( function () { hoverLayerElementsContainer.appendTo($('body')); });

function closeHoverLayerElement() {
	if (hoverLayerElement) {
		hoverLayerElement.stop().css('height', 'auto').hide();
		hoverLayerElementTarget.removeClass('sel');
		hoverLayerElement = null;
		hoverLayerElementTarget = null;
		lastHoverLayerElementTarget = null;
	}
}
jQuery.fn.makeHover = function(refElem, alignType) {
	if (hoverLayerElementTarget && refElem.isChild(hoverLayerElementTarget)) { // Child of target
		return this; // Do not anything
	}
	closeHoverLayerElement();
	hoverLayerElement = this;
	hoverLayerElementTarget = refElem;
	hoverLayerElementTarget.addClass('sel');
	hoverLayerElement.sameOffset(refElem, alignType).slideDown(150);
	return this;
}







// Mouse and keys management

/* Layers closing by click on a background*/
$(document).click( function (e) {

		if (popupLayerElement != null) {
			e ? evt = e : evt = event;
			var CSE = evt.target ? evt.target : evt.srcElement;
			if (!$(CSE).isChild(popupLayerElement) && (CSE != popupLayerElementTarget.get(0))) closeLastPopupLayerElement();
		}
		
		if (formLayerElement != null) {
			e ? evt = e : evt = event;
			var CSE = evt.target ? evt.target : evt.srcElement;
			if (!$(CSE).isChild(formLayerElement) && (CSE != formLayerElementTarget.get(0))) closeLastFormLayerElement();
		}

	return true;
	
});

$(document).mouseover( function (e) {
	if (hoverLayerElement != null) {
		e ? evt = e : evt = event;
		var CSE = evt.target ? evt.target : evt.srcElement;
		if (!$(CSE).isChild(hoverLayerElementsContainer) && !$(CSE).isChild(hoverLayerElementTarget)) closeHoverLayerElement();
	}
	return true;
});




// Global key management
$(document).keydown( function(e) {
  if (e == null) { // ie
    keycode = event.keyCode;
  } else { // mozilla
    keycode = e.which;
  }
  if(keycode == 27) { // escape, close floating layers
    closeLastPopupLayerElement();
    closeHoverLayerElement();
    closeModal();
  } 
  if (keycode == 13) { // Enter
  	if ($("#popupQuestionYes").size() > 0) {
  		$("#popupQuestionYes").click();
  		return false;
  	}
  }
});



// Initialize modal layer
			
			var overlay;
			var overlayContainer;
			var overlayIFrame;
			var modalIsActive = false;
			
			$(function() {	
				/* Modal layer initialization */
				overlay = $('<div>')
					.css({
						opacity: 0.4,
						height: '100%',
						width: '100%',
						position: 'fixed',
						left: 0,
						top: 0,
						zIndex: 3000,
						background: 'black',
						cursor: 'wait'
					})
					.appendTo('body').hide();
						
				overlayContainer = $('<div>')
					.css({
						position: 'absolute', 
						textAlign: 'center',
						zIndex: 3100
					}).appendTo('body').hide();
				
				// fix issues with IE and create an iframe
				if ($.browser.msie) {			
					
					var wHeight =  $(document).height() + 'px';
					var wWidth = $('body').width() + 'px';
				
					// position hacks
					overlay.css({position: 'absolute', height: wHeight, width: wWidth});
					overlayContainer.css({position: 'absolute'});
				
					// add an iframe to prevent select options from bleeding through
					overlayIFrame = $('<iframe src="javascript:false;">')
						.css({
							opacity: 0, 
							position: 'absolute',
							height: wHeight,
							width: wWidth,
							zIndex: 1000,
							width: '100%',
							top: 0,
							left: 0
						})
						.appendTo('body').hide();
				}
			});
			
			
			jQuery.fn.showAsModal = function(width) {
				overlayContainer.html("");
				$(this).appendTo(overlayContainer);	
			  	if (overlayIFrame) overlayIFrame.show();
				overlay.fadeIn(300);
				if (width !== undefined) {
					overlayContainer.css("width", width);
				} else {
					overlayContainer.css("width", "auto");
				}
				overlayContainer.show().centerScreen();	
				modalIsActive = true;	
			}
			
			function closeModal() {
				if (overlayIFrame) overlayIFrame.hide();
				overlay.fadeOut(150);
				overlayContainer.fadeOut(150).html(""); // Close and remove modal content
				modalIsActive = false;
			}
			


function modalElement(element, width, height) {
	element.appendTo(overlayContainer);
	if (overlayIFrame) overlayIFrame.show();
	overlay.fadeIn(300);
	if 	(width !== undefined) {
		overlayContainer.css("width", width);
	}
	overlayContainer.css({
		top: '120px'
	}).show();
	$("#popupCloser").attachSafeClick(function(){ // Close this modal
		closeModal();
		return false;
	}).addHoverAbility();	
}

function modalUrl(url, width) {
	return $.get(url, null, function (data) {
 		overlayContainer.html(data);
  				
   		if (overlayIFrame) overlayIFrame.show();
		overlay.fadeIn(300);
		
		if 	(width !== undefined) {
			overlayContainer.css("width", width);
		}
		
		overlayContainer.css({
			top: '120px'
		}).show();
	
		// Closing modal
		$("#popupCloser").attachSafeClick(function(){ // Close this modal
			closeModal();
			return false;
		}).addHoverAbility();

		// Sending form
 		$(overlayContainer.find("form")).submit( function () {			
	  		var backUrl = overlayContainer.find("input[name=backUrl]");
			if (backUrl) {
				var originalUrl = window.location.toString()
				var redirectUrl = backUrl.val();
				var newLocation = redirectUrl.replaceAll("&amp;", "&");
				var newHref = newLocation + "#pos" + $(window.document).find("body").scrollTop();
				var oldLocation = window.document.location.pathname + window.document.location.search;
				window.location.assign(newHref);
				if (oldLocation == newLocation) {
					window.location.reload();
				}
			} else {
				window.location.reload()
			}
			overlayContainer.fadeOut(500);
			return false;
		});
	});	
}


function modalImage(url, width) {
	overlayContainer.html('<img class="popupImage" src="'+url+'" />');
	
  	if (overlayIFrame) overlayIFrame.show();
	overlay.fadeIn(300);

	if 	(width !== undefined) {
		overlayContainer.css("width", width);
	}
	
	overlayContainer.css({
		top: (jQuery(window).scrollTop() - -32) + 'px'
	}).show().centerH();

	// Closing modal
	$(".popupCloser").attachSafeClick(function(){ // Close this modal
		closeModal();
		return false;
	}).addHoverAbility();

	overlayContainer.find("img").attachSafeClick(function(){ // Close this modal
		closeModal();
		return false;
	}).css("cursor", "pointer");
	
	
	
	return false;
}





// For colorPicker
var DefinedPalletes = new Array;
function registerPallete(className, params, rows) {
	DefinedPalletes[DefinedPalletes.length] = new Array (className, params, rows);
}




// Other helper objects
var focusedElement = null;


// JavaScriptUtils commons register to element
jQuery.fn.registerCommons = function() {

	
	// Elements groups cache, these groups are available through the whole common procedure
	var allForms = $("form");
	var allTables = $("table");
	var allAnchors = $("a");	


	// Load currently focused element to focusedElement 
	allForms.find("input, textarea, select, a").focus( function() {
		if (formLayerElement && !$(this).isChild(formLayerElement))
			closeLastFormLayerElement();
		focusedElement = this;
	});
	
	// PNG Fix	
	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
	if ($.browser.msie && (ie55 || ie6)) {
		this.find("img[src$=.png]").each(function() {
			var elem = $(this);
			elem.attr('width', elem.width());
			elem.attr('height', elem.height());
			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (elem.attr('id')) ? 'id="' + $(this).attr('id') + '" ' : '';
			var imgClass = (elem.attr('class')) ? 'class="' + $(this).attr('class') + '" ' : '';
			var imgTitle = (elem.attr('title')) ? 'title="' + $(this).attr('title') + '" ' : '';
			var imgAlt = (elem.attr('alt')) ? 'alt="' + $(this).attr('alt') + '" ' : '';
			var imgAlign = (elem.attr('align')) ? 'float:' + $(this).attr('align') + ';' : '';
			var imgHand = (elem.parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);
			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + elem.width() + 'px;' + 'height:' + elem.height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + elem.attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + elem.width() + 'px;' + 'height:' + elem.height() + 'px;'+'">' + strNewHTML + '</span>';
			}
			elem.hide();
			elem.after(strNewHTML);
		});
	}

	// External links fix
	this.find("a[rel=external]:not(.popup)").attachSafeClick(function() {
		attrHref = $(this).attr('href');
	
		// Only for Tahuti demo - will be improved
		if ($(this).attr('demoPreLink') != undefined) {
			timerID = 0;

			$('body').css('cursor', 'wait !important');
			
			preRequest = $(document.createElement('iframe'));
			preRequest.attr('src', "http://demo.tahuti.cz/logout.do");
			preRequest.hide();
			preRequest.appendTo('body');
			
			preRequest = $(document.createElement('iframe'));
			preRequest.attr('src', $(this).attr('demoPreLink'));
			preRequest.hide();
			preRequest.appendTo('body');
			myFunc = function() {
				$('body').css('cursor', 'inherited');
				window.open(attrHref);	
			}
			timerID = self.setTimeout(myFunc, 600);

		} else {
			window.open(attrHref);	
		}

		return false;
	});
	
	// Popup windows
	this.find("a.popup").attachSafeClick(function(e){
		var anchor = $(this);
		var x;
		var y;		
		var width = anchor.getClassParam("width");
		var height = anchor.getClassParam("height");
		if (!width) width = 380;
		if (!height) height = 200;
		if (anchor.hasClass('popupNearby')) {
			if (e.screenX && e.screenY) {
				x = e.screenX;
				y = e.screenY;
			}			
			if ((x + width) > screen.availWidth) {
				x = x - width;
				x -= 10;
			} else {
				x += 10;
			}
			if ((y + height) > screen.availHeight) {
				y = y - height;
				y -= 10;
			} else {
				y += 10;
			}
		} else {
				x = anchor.getClassParam("x");
				y = anchor.getClassParam("y");
		}
		
		if (!x) x = (window.screenX ? window.screenX : 0) + Math.round(((window.window.outerWidth ? window.window.outerWidth : screen.availWidth ) / 2) - (width / 2));
		if (!y)y = (window.screenY ? window.screenY : 0) + Math.round(((window.window.outerHeight ? window.window.outerHeight : screen.availHeight) / 2) - (height / 2));	
		
		openPopupWindow(anchor.attr("href"), anchor.attr("title"), x, y, width, height);
		return false;
	});
	
	// Automatic table TR hover to .hoverable tables
	this.find('table.hoverable tr').addHoverAbility();

	// Anchor is expanded to whole tr
	function executeTrAnchor () {
		var anchor = $(this).find('.toTr').eq(0);
		if (anchor.data('modifiedLink')) anchor.click();
		else self.location = anchor.attr('href');
	}
	this.find('table tr a.toTr, table tr input.toTr, table tr button.toTr').parents('tr').click(executeTrAnchor).keypress(executeTrAnchor).css('cursor', 'pointer').addHoverAbility();

	// Anchor is expanded to parent element
	function executeParentAnchor () {
		var anchor = $(this).find('.toParent').eq(0);
		if (anchor.data('modifiedLink')) anchor.click();
		else self.location = anchor.attr('href');
	}
	this.find('a.toParent, input.toParent, button.toParent').parent().click(executeParentAnchor).keypress(executeParentAnchor).css('cursor', 'pointer').addHoverAbility();

	this.find('a.popupImage').attachSafeClick(function() {
		modalImage($(this).attr("href"), '100%');
		return false;
	});

	// Anchor or input with toParentEx class is expanded to parent's parent element
	function executeParentAnchorEx () {
		var anchor = $(this).find('.toParentEx').eq(0);
		if (anchor.data('modifiedLink')) anchor.click();
		else self.location = anchor.attr('href');
	}
	this.find('a.toParentEx, input.toParentEx, button.toParentEx').parent().parent().click(executeParentAnchorEx).keypress(executeParentAnchorEx).css('cursor', 'pointer').addHoverAbility();

	// Paragraph classed as noJsWarning is removed
	$("p.noJsWarning").remove();

	// Autoscroll
	var pageUrl = document.location.toString();
	if (pageUrl.lastIndexOf('#pos') != -1) $(document).scrollTop(pageUrl.substring(pageUrl.lastIndexOf('#pos') + 4));
	
	// Popups
	$("#popupCloser").attachSafeClick(function(){
		window.close();
		return false;
	}).addHoverAbility();
	
	$("a.openParent").attachSafeClick(function(){	
		window.opener.location.assign($(this).attr('href'));
		window.close();
		return false;
	});
	
	$("a.popupQuestion").attachSafeClick(function(){		
		var popupQuestionUrl = $(this).attr('href');	
		var modalQuestionBox = $('<div id="popupQuestionFrame"><p id="popupQuestionMessage"></p>'+
			'<div><button id="popupQuestionYes">'+messageKey['yes']+'</button>'+
			'<button id="popupQuestionNo">'+messageKey['no']+'</button>'+
			'</div></div>'
		);	
		modalQuestionBox.find("#popupQuestionMessage").text($(this).attr('title'));				
		modalQuestionBox.find("#popupQuestionNo").attachSafeClick(function(){ // Close this modal
			closeModal();
			return false;
		});	
		modalQuestionBox.find("#popupQuestionYes").attachSafeClick(function(){ // Close this modal
			window.location.assign(popupQuestionUrl).attr("href");
			return false;
		}).get(0).focus();
		
		modalQuestionBox.showAsModal();
		return false;	
	});
	
	// Form focus classing
	$("input.txt, textarea").focus(function() {
		$(this).addClass("focus");
	}).blur(function() {
		$(this).removeClass("focus");
	});
	
	// Form errors style delegated to lines
	$("p.error").parents("tr").addClass('error');
	
	return this;
	
}



jQuery.fn.displayTime = function() {
	var timeElement = this;
	function updateClock () {
		var currentTime = new Date();
		var innerContent = '';
		if (!bHideDate) innerContent = formatFieldDate(currentTime.getDate(), currentTime.getMonth() + 1, currentTime.getFullYear()) + ' ';
		if (bShowSeconds) innerContent += formatFieldTime(currentTime.getHours(), currentTime.getMinutes(), currentTime.getSeconds());
		else innerContent += formatFieldTime(currentTime.getHours(), currentTime.getMinutes());						
		timeElement.html(innerContent);
	}
	var bHideDate = this.hasClass('hideDate');
	var bShowSeconds = this.hasClass('showSeconds');
	setInterval(updateClock, 1000);
	updateClock();
}




$(function() {
	$('body').registerCommons();
});

