/* rxLib - RASAMAX Library
SIA RASAMAX - 2009

Requirements:
jQuery - http://jquery.com
jQuery UI - http://jqueryui.com
jQuery.form - http://malsup.com/jquery/form/
Jeditable - http://www.appelsiini.net/projects/jeditable
livequery - http://plugins.jquery.com/project/livequery/

*/

//////////////////////////////////////////////////////////////
// rx-tools
// Common tools to be used on a page
//////////////////////////////////////////////////////////////

if (!rx) var rx = {};

rx = $.extend(rx, {
// jQuery UI dialog confirm box
confirm : function (message, yesAction, noAction) {
var buttons = {};
buttons[rx.translate('no')] = function () {if (noAction) noAction();$(this).dialog('close');};
buttons[rx.translate('yes')] = function () {yesAction();$(this).dialog('close');};
var rxConfirm = $('<div class="rx-confirm"></div>');
$(rxConfirm).css({display:'none'}).appendTo('body').dialog({
autoOpen : true,
title : rx.translate('confirm'),
show : 'scale',
hide : 'scale',
modal : $.browser.msie ? false : true,
buttons : buttons,
open : function (event, ui) {
	// setTimeout because "open" and "focus" shoot before dialog is on screen (if effect is used)
	setTimeout(function() {$('button:nth-child(2)',$(rxConfirm).parent())[0].focus();},500);
	},
close : function () {
	// Remove if exists for redefining
	$(rxConfirm).remove();
	}
}).html(message);
// Show confirm
//$(rxConfirm).html(message).dialog('open');
},

// jQuery UI dialog alert box
alert : function (message) {
var buttons = {};
buttons[rx.translate('ok')] = function () {$(this).dialog('close');};
// Create message box
var rxAlert = $('<div class="rx-alert"></div>');
$(rxAlert).css({display:'none'}).appendTo('body').dialog({
title : rx.translate('message'),
show : 'scale',
hide : 'scale',
modal : $.browser.msie ? false : true,
buttons : buttons,
open : function (event, ui) {
	// setTimeout because "open" and "focus" shoot before dialog is on screen (if effect is used)
	setTimeout(function() {$('button:nth-child(1)',$(rxAlert).parent())[0].focus();},500);
	},
close : function () {
	// Remove if exists for redefining
	$(rxAlert).remove();
	}
}).html(message);
},



// Ajax history (back/forward buttons support)
history : function (historyAnchor) {
if (historyAnchor.indexOf('#')==-1) historyAnchor = '#'+historyAnchor;
if (historyAnchor.indexOf('?')!=-1) historyAnchor = historyAnchor.replace(/\?/,'');
window.location.hash = historyAnchor;
},

// Current hash state of window
hashState : '',

// Catch window.location.hash change and make a request
historyCheck : function () {
// Future: change to an onhashchange event
//if (typeof(oldHashState)=='undefined') oldHashState='';
if (window.location.hash!=rx.hashState) {
	rx.hashState = window.location.hash;
	// For now direct request to different sources depending on request paramteres
	// Redirect to login screen if "/admin" is found
	if (rx.hashState.indexOf('/admin')!=-1) {
		window.location.href = window.location.pathname+'/admin';
	}
	// Call category if "cid" is found
	if (rx.hashState.indexOf('cid=')!=-1) {
		//$('#main_refresh_frame_div').load('main.php'+rx.hashState.replace(/\#/,'?'));
		
		$.getJSON('actions.php?action=openCategory'+rx.hashState.replace(/\#/,'&'),null,function(response) {
			//alert(response.responseHTML);
			//$.jGrowl(response.responseHTML);
			//if (response.responseHTML)
				$('#main_refresh_frame_div').html(response.responseHTML);
			// When changing category in menu if scrollbar is moved down place it on the top (0px from the top)
			if($('.rx-main').scrollTop()>0) {
				$('.rx-main').scrollTop(0);
			}
			if ($('.rx-main').css('overflow')=='visible') rx.correctIeTableHeight();
			document.title = response.title;
			changeLogoImage(response.changeLogoImage ? response.changeLogoImage : '', response.changeBackgroundImage ? response.changeBackgroundImage : '');
			//This will enable AddThis script to work also on ajax pages
			rx.addThisInit();
		});
		}
	else {
		rx.hashState = window.location.hash;
		/*$.getJSON(window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1)+rx.hashState.replace(/\#/,'?'),null,function(data,textStatus){
			alert(data.responseText);
		});*/
	}
}
setTimeout(function(){rx.historyCheck();},1000);
},

translate : function(wordKey) {
	return words[wordKey] ? words[wordKey] : wordKey;
},

addThisInit : function() {
				var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
    		if ( window.addthis ) {
        		window.addthis = null;
    		}
    		$.getScript( script );
},

// Outputs a function information on execution
trackFunctions : function (functionCommandString) {
if (rx.debug) console.log(functionCommandString);
},

getScriptPath : function (scriptName) {
var path = '';
$('script[src]').each(function() {
	if(this.src.indexOf('/'+scriptName)!=-1) {
	path = this.src.substr(0, this.src.lastIndexOf('/')+1);
	path = path.replace(window.location.protocol+'//'+window.location.hostname,'');
	}
	else {
		// This will work only if we are compressing js files
		var pathVar = scriptName.substring(0,scriptName.lastIndexOf('.'))+"Path";
		eval("if(typeof("+pathVar+")!='undefined') path = "+pathVar+";");
	}
});
return path;
},

keepAlive : function () {
$.getJSON('actions.php?action=keepAlive', function(res) {
	$('#usersOnline').empty();
	if (res.usersOnline)
		$.each(res.usersOnline, function(i, userOnline) {
			$('#usersOnline').append((i ? ', ' : ' ') + userOnline.name);
			});
	if(res.refreshPage) location.href = location.pathname;
});
},

refresh : function() {
	window.location.href=window.location.pathname;
},

// Refresh validation code images
refreshValidationCode : function() {
	$('.rx-validation-image').attr('src',$('.rx-validation-image').attr('src')+'?refresh='+Math.random());
},
// This function will resize gallery images depending on percent selected by user
galleryResize:function(articleId, sizePercent){
	var gallery = $('.rx-article[articleid='+articleId+'] .gallery');
	// Resize div's in the thumbnail list 
	$(gallery).find('.thumbnailsList div').css({'height':+Math.round(130/100*sizePercent)+'px','width':Math.round(150/100*sizePercent)+'px','padding-bottom':Math.round(10/100*sizePercent)+'px'}).end()
		// Resize link containig image
		.find('.thumbnailsList a').css({'height':Math.round(104/100*sizePercent)+'px','width':Math.round(150/100*sizePercent)+'px','padding-top':Math.round(10/100*sizePercent)+'px'}).end()
		// Resize image
		.find('.thumbnailsList img').css({'padding':Math.round(6/100*sizePercent)+'px','max-width':Math.round(120/100*sizePercent)+'px','max-height':Math.round(90/100*sizePercent)+'px'});
	// If we need to show only one line with thumbnails then resize thumbnail container
	if($(gallery).attr('compactMode')==1){
		$(gallery).find('.thumbnailsList').css({'height':Math.round(140/100*sizePercent)+'px'})
	}
},

// Function to fix IE problem of incorrectly expanding <table> cells
correctIeTableHeight: function(){
	// Need to fix table columns height only in IE because other browsers are MORE smarter
	if(!$.browser.msie) return; 
	// Get the main section
	var main = $('#object_cell_main_0');
	// This will represent main height with margin (true), padding and border - find rx-main because ometimes main section is stretched and e can't use that height 
	var mainHeight = main.find('.rx-main').outerHeight(true);
	// Get main rowspan to find out how many rows we need to check
	var mainRowspan = main.attr('rowSpan');
	// Get index of the first row in the table where main section starts
	var mainRowIndex = main.parent().index();
	//alert('a');
	// Go through all columns in design, since we don't know exact column count set max column count as 100 and break from cycle if column is not found.
	for (var i=1; i<100; i++){
		// Get column by index
		var column = $('#page_border_table > tbody > tr > td').nthCol(i);
		// Array to store cells with no height defined
		var noHeightCells = new Array();
		// Here we will store height of the column
		var columnHeight = 0;
		// If column exists then process it
		if(column.size()){
			// Check each cell in column
			column.each(function(ii, val){
				// rowIndex will be the number of the row where current element is found
				var rowIndex = $(this).parent().index();
				// Check heights only for rows in one line with main section (for example do nothing with footer or logo)				
				if(rowIndex>=mainRowIndex && rowIndex<=(mainRowspan+mainRowIndex-1)){
					// Current row css height
					var cellHeight = 0;
					if($(this).css('height')!='auto'){
						cellHeight = parseInt($(this).css('height'),10);
					}
					// If row css height is not set or there is an attribute no_height change row height
					if(isNaN(cellHeight)|| cellHeight==0 || $(this).attr('no_height')){
						// If main section is smaller than this column remove height - then it will be sized normally 
						if(columnHeight>=mainHeight){
							$(this).removeAttr('height');
						}
						else{
							// Get margin, padding, and border height sum for the element
							var boxHeight = $(this).outerHeight(true)-$(this).height();
							// Calculate height for the element	if it's negative set is as 1 otherwise it will produce javascript error				
							cellHeight = mainHeight-columnHeight-boxHeight;
							if(cellHeight<=0){
								cellHeight = 1;
							}
							// Set element height
													
							$(this).attr('height',cellHeight);
							// Set no_height attribute (will use it next time when calculating height as a flag that we need to calculate height for this element)
							$(this).attr('no_height','1');
							// Put cell we need to fix into an array
							var cellArrayIndex = noHeightCells.length;
							noHeightCells[cellArrayIndex] = $(this);
						}
					}
					// If css height is set then use it, no calculation is needed (when calculating column height use maximum - cell height or cell content height)
					else{
						columnHeight = columnHeight + Math.max(cellHeight,$(this).children().height()); //Compare with content
					}
				}
			}); // End of each
			// Column height just for newly resized items 
			var columnHeightNew = 0;
			// Correct height for cells with no height set
			if(noHeightCells.length){
				$.each(noHeightCells, function(index, value) {
					// Box height of the element (margin,padding,border)
					var boxHeight = $(this).outerHeight(true)-$(this).height();
					// For each cell without height set equal height if it's negative then set it as 1 otherwise there will be a javascript error
					var newHeight = ((mainHeight-columnHeight)/noHeightCells.length)-boxHeight;
					if(newHeight<=0){
						newHeight = 1;
					}
					$(this).attr('height',newHeight);
					columnHeightNew = columnHeightNew + $(this).height();
				});
				
				// If column is bigger than main section resize it again
				if((columnHeight+columnHeightNew)>mainHeight){
					var fitHeight = (columnHeight+columnHeightNew-mainHeight)/noHeightCells.length;
					$.each(noHeightCells, function(index, value) {
						// If fitHeight is smaller than element outer height then use element outer height (height with paddings borders and margins) - otherwise in some cases elements will be not resized correctly
						if($(this).outerHeight(true)>fitHeight){
							$(this).attr('height',($(this).outerHeight(true)+2));
						}
						else{
							$(this).attr('height',fitHeight);
						}	
					});
				}
				
			}
		}
		// If column is not found then it means that there will be no more columns, we can break out of cycle
		else{
			break;
		}
	} // End of for
	// Variable to show if we have any images that are not completed now (still loading)
	var loadingImg = false;
	// Get all images which are not broken ones
	$('img:not([onerror][src$=#])').each(function(){
		// If image is still loading
		if(this.readyState!='complete'){
			loadingImg = true;
		}
	});
	// If we have images loading then recall correctIeTableHeight function after timeout
	if(loadingImg){
		setTimeout("rx.correctIeTableHeight();",1000);
	}
} // End of correctIeTableHeight function

});

// LiveQuery

// Hoverable icons
$('.ui-state-default').livequery(function() {
	$(this).hover(
	function(){ $(this).addClass('ui-state-hover'); }, 
	function(){ $(this).removeClass('ui-state-hover'); }
	);
	},
	function() { 
		// unbind the mouseover and mouseout events 
		$(this).unbind('mouseover').unbind('mouseout'); 
	}
);


// rx-colorpicker
$('.rx-colorpicker').livequery(function () {
$(this).addClass('ui-corner-all');
if (!this.id) this.id='c'+Math.round(Math.random()*1000);
var id = this.id;
var color = /^#?([0-9a-f]{3}){1,2}$/i.test(this.value) ? this.value : '';
$(this)
.css('background-color',color)
.one('click',function() {
	$(this).ColorPicker({
	color: color,
 	onShow: function (colpkr) {
 		// Append to body for correct positioning
 		$(colpkr).appendTo(document.body);
		$(colpkr).fadeIn(500);
		$(this).ColorPickerSetColor($(this).val());
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500,function() {
			// Place colorpicker near element so it is removed from DOM on element remove
			$(colpkr).insertAfter('#'+id);
		});
		return false;
	},
	onSubmit: function(hsb, hex, rgb, el) {
		$(el).val('#'+hex);
		$(el).css('backgroundColor', '#' + hex);
		$(el).ColorPickerHide();
	},
	onChange: function (hsb, hex, rgb) {
		$('#'+id).change();
		$('#'+id).css('backgroundColor', '#' + hex).val('#' + hex);
	}
	});
	$('#'+id).click();
});
});


/*
rx-uploader

ID is obligate for input[type=file]
if REL is set for SELECT then
	rx-uploader will append uploaded file name to it and run it's change() event
else
	rx-uploader will append uploaded file name to a select element with ID = rx-uploader.ID - '_file' and run it's change() event
Requires uploadFile.php with move_uploaded_file();
*/
$("input[type=file].rx-uploader").livequery(function() {
	if (!this.id) this.id='rxUploader'+Math.round(Math.random()*1000);
	var id = this.id;
	$(this).uploadify({
	'uploader'		: 'script/jquery/uploadify/uploadify.swf',
	'script'		: 'uploadFile.php',
	'scriptData'	: {sessionId : PHPSESSID},
	'cancelImg'		: 'script/jquery/uploadify/cancel.png',
	'buttonText'	: 'Upload',
	'height'		: 20,
	'width'			: 20,
	//'hideButton'	: true
	//'wmode'		: true,
	'buttonImg'	 	: 'script/jquery/uploadify/icon.png',
	//'queueID'		: 'fileQueue',
	'auto'			: true,
	'multi'			: false,
	'fileDesc'		: 'Upload files you want',
	'fileExt'		: '*.jpg;*.jpeg;*.png;*.gif;*.swf',
	'onSelect'		: function(event,queueID,fileObj) {
		//alert(fileObj.name+' is selected');
	},
	'onComplete'	: function(event,queueID,fileObj,response) {
		fileObj.name = response;
		var selectId = id.substring(0,id.lastIndexOf('_'));
		// If element is not found by subId then use REL
		if (!selectId)
			selectId = $('#'+id).attr('rel');
		$('#'+selectId).val(fileObj.name);
		if (!$('#'+selectId).val())
			$('#'+selectId).append('<option value="'+fileObj.name+'" selected>'+fileObj.name);
		$('#'+selectId).change();
	},
	'onError'		: function(event,queueID,fileObj) {
		alert(fileObj.name+' was not uploaded');
	}
});
});
// Queue to hover near upload tool
$('.uploadifyQueue').livequery(function() {$(this).css({position:'absolute'});});




// Replace HTML radio buttons (with lavels) with buttons
$('.rx-ui-buttonset').livequery(function () {
	$(this).buttonset();
},
function () {
	$(this).button("destroy");
}
);



// Replace HTML radio buttons (with lavels) with buttons
$('.rx-ui-button').livequery(function () {
	$(this).button();
},
function () {
	$(this).button("destroy");
}
);


// this will enable datepicker for all elements with class rx-datepicker
$('.rx-datepicker').livequery(function () {
	$(this).datepicker({ dateFormat: 'yy-mm-dd' });
});


$('.rx-numeric').live('keydown',function(event) {
// Allow only backspace, delete, dot and tab
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || event.keyCode == 9 ) {
	// let it happen, don't do anything
} else {
	// Ensure that it is a number and stop the keypress
	if (event.keyCode < 48 || event.keyCode > 57 ) {
	event.preventDefault(); 
	} 
}
});


// Addon for valudate jQuery plugin
// Validate multi email (emails separated by , or ;) field
if ($.validator) {
$.validator.addMethod("multiMail", 
function(value, element) {
	// if addresses are empty do not check anything further
	if($(element).val()==''){
		return true;
	}
	// if there some ; between e-mail addresses replace it with , (so if users use ; or , as a separator between emails it's doesn't matters)
	// split email addresses
	var addressesSplit =(($(element).val()).replace(/;/gi,',')).split(',');
	// error count
	var error = 0;
	// check each email address
	for (i=0;i<addressesSplit.length;i++){
		// if address is not an email address increase error count
		if (!addressesSplit[i].match(/^[a-z0-9_\.\-]+\@[a-z0-9\-\.]+\.[a-z]{2,4}$/i)){
			error++;
		}
	}
	if (error>0) return false; 
	else return true;
}, 
"Wrong e-mail address");

// Validate that field has only alphanumeric values
$.validator.addMethod("alphaNumber", 
function(value, element) {
	// if field is empty do not check anything further
	if($(element).val()==''){
		return true;
	}
	// if value contains only alphanumeric characters then it's valid
	if ($(element).val().match(/^[A-Z0-9]{7,20}$/)){
		return true;
	}
	return false;
}, 
"Enter only alphanumeric characters");
}


$(function () {

//This will hide up, down and show all buttons for the gallery if gallery content fits in one line
$('body').delegate('.gallery .thumbnailsList', 'hover',function() {
	if($(this).attr('scrollHeight')<=Math.round(140/100*$(this).parent().attr('thumbSize'))){
		$(this).find('.thumbnailsScroll').hide();
	}
});

$('body').delegate('.gallery button', 'click',function() {
	var scrollNew = 0;
	// Calculate image row height using percent value, since user now can resize thumbnails
	var rowHeight = Math.round(140/100*$(this).parents('.gallery').attr('thumbSize'));
	// Current scrollTop 
	var thumbnailsList = $(this).parents('.gallery').find('.thumbnailsList');
	var scrollHeight = thumbnailsList.attr('scrollHeight');
	var buttonIdx = $(this).index();
	var scroll = thumbnailsList.scrollTop();
	// If button UP pressed
	if (buttonIdx == 0) {
		scrollNew = scroll - rowHeight;
	}	
	// If button Down presses
	if (buttonIdx == 2){
		scrollNew = scroll + rowHeight;
		// If there is less space down than a 1 gallery row size then it means that there are no images and we don't need to scroll down
		if(scrollHeight-scrollNew<rowHeight){
			scrollNew = scroll;
		}
	}
	// make animated scroll
	thumbnailsList.animate({scrollTop: scrollNew}, 1000);
	// if button remove overflow pressed
	if(buttonIdx == 1){
		var imgContHeight = thumbnailsList.height();
		var otherButtons = thumbnailsList.find('button:not(:eq('+buttonIdx+'))');
		if(imgContHeight==rowHeight){
			// set scroll buttons bottom as auto - otherwise buttons will be shown at the bottom
			thumbnailsList.find('.thumbnailsScroll').css({'bottom':'auto'});
			// show all thumbnails not just one row of them
			imgContHeight = scrollHeight;
			thumbnailsList.animate({height: imgContHeight+'px'}, 1000 );
			// hide up and down buttons
			otherButtons.hide();
		}
		else{
			// set scroll buttons bottom as 0 - otherwise buttons will be shown at the bottom
			thumbnailsList.find('.thumbnailsScroll').css({'bottom':'0'});
			// show only one row of thumbnails
			thumbnailsList.animate({height: rowHeight+'px'}, 1000 );
			// show up and down buttons
			otherButtons.show();
		}
	}
});



// Set current "cid" in address bar or catch current hash for stopping unneeded requests
if ($('.rx-menu').size() && $('.rx-menu li:has(table.selected):first').size()) {
	var id = $('.rx-menu li:has(table.selected):last').attr('id').match(/category_m([0-9]*)g([0-9]*)_li/);
	var cid = "#cid="+id[2]+(id[1]!='0'?'&mid='+id[1]:'');
}

if (!window.location.hash && !window.location.href.match(/cid=([0-9]*)/)) {
	// Firefox requires setTimeout, otherwise it drops favicon to FWK default
	if (cid) setTimeout(function(){
		window.location.hash = cid;
		rx.hashState = window.location.hash;
		},1000);
}
else if (window.location.hash == cid)
	// Set "hashState" before "historyCheck" otherwise current category content will be reloaded again
	rx.hashState = window.location.hash;
rx.historyCheck();
rx.keepAlive();
setInterval(function(){rx.keepAlive();},60000);
});

