/*
OOOGUI - Obliquid Object Oriented Graphic User Interface

OOOGUI is a dynamic CMS that lets you define your data structure 
(objects, relations between objects, queries on objects), and lets
you create public and private HTML pages to view and modify your 
contents.  All through a WYSIWYG interface. 
OOOGUI is multilingual, manages role based permissions, and 
generates for you PHP and SMARTY code that you can customize on 
your needs.

Copyright (C) 2010 Federico Carrara (federico@obliquid.it)

For more information http://obliquid.org/

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/




/* THINGS TO DO IMMEDIATELY */


// admin popup start 
var itemId = "";
var itemLabel = "";
var action = "";
var objectId = "";
var preassignedRelations = "";
var preassignedProperties = "";
function openAdminPopup( id_item, label_object, id_object,  action, preassignedRelations, preassignedProperties )
{
	this.itemId = String(id_item);
	this.itemLabel = label_object;
	this.objectId = String(id_object);
	this.action = action;
	this.preassignedRelations = preassignedRelations;
	this.preassignedProperties = preassignedProperties;
	//alert (this.preassignedProperties);
	//this.preassignedProperties = "ciao";
	window.open("main.php?openerHasVars=yes", 'adminPanel', 'width=1015, height=500, resizable, status, scrollbars=1, location');
}
// admin popup end 


// login module start 
function submitLogin(field)
{
	document.getElementById("loginForm").submit();
}		
function submitLoginOnEnter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	   {
			document.getElementById("loginForm").submit();
			return false;
	   }
	else
	   return true;
}
// login module end 	

//showCrudBox
function toggleCrudBox(item)
{
	var crudBox = item.childNodes[0];
	if ( crudBox.style.display == "block" )
	{
		crudBox.style.display = "none";
	}
	else
	{
		crudBox.style.display = "block";
	}
}		

function showCrudBox(item)
{
	var crudBox = item.childNodes[0];
	crudBox.style.display = "block";
}		

function hideCrudBox(item)
{
	var crudBox = item.childNodes[0];
	crudBox.style.display = "none";
}		


//adminBox

function toggleAdminBox(item)
{
	adminBox = $(item).children(".adminBoxTable");
	
	if ( $(item).closest(".adminDiv").children().filter('.adminDivBg').length > 0 )
	{
		//esiste già il fondino, allora lo tolgo
		$(".adminDivBg").remove();
		//e faccio sparire l'adminBox
		adminBox.css({display: 'none'});
	}
	else
	{
		//il mio div non ha fondino, quindi lo creo
		//rimuovo qualunque fondino già esistente, e chiudo qualunque adminBox
		$(".adminDivBg").remove();
		$(".adminBoxTable").css({display: 'none'});
		
		//creo un fondino per il div selezionato
		fondino = $("<div class='adminDivBg'></div>");
		//fondino.css({display: 'none'});
		
		fondino.height( $(item).closest(".adminDiv").height() );
		fondino.width( $(item).closest(".adminDiv").width() );
		//posiziono il fondino sopra al div
		/*
		eleOffset = $(item).closest(".adminDiv").offset();
		*/
		//fondino.css({display: 'block'});
		//fondino.offset({ top: 0, left: 0 });
		$(item).closest(".adminDiv").append( fondino );
		
		//e faccio comparire l'adminBox
		adminBox.css({display: 'block'});
		
		//deseleziono l'adminDiv
		unselectDiv(item);
	}
	
	/*
	var crudBox = item.childNodes[0];
	if ( crudBox.style.display == "block" )
	{
		crudBox.style.display = "none";
	}
	else
	{
		crudBox.style.display = "block";
	}
	*/
}		



function selectDiv(item)
{
	//evidenzio il div
	$(item).closest(".adminDiv").addClass("adminDivSelected");
}		

function unselectDiv(item)
{
	//tolgo evidenziazione dal div
	$(item).closest(".adminDiv").removeClass("adminDivSelected");
}		







//vtip start
this.vtip = function() {    
    this.xOffset = -4; // x distance from mouse
    this.yOffset = -70; // y distance from mouse       
    
    $("[title]").unbind('hover').hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
            
            $('body').append( '<p id="vtip">' + this.t + '</p>' );
                        
            //$('p#vtip #vtipArrow').attr("src", 'javascripts/jq/plugin/vtip/images/vtip_arrow.png');
			
            $('p#vtip').css("top", this.top+"px").css("left", this.left+"px").delay(600).fadeIn("slow");
            
        },
        function() {
            this.title = this.t;
            $("p#vtip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
			if ( this.top < 0 ) this.top = 0;
            this.left = (e.pageX + xOffset - ( $('p#vtip').width() / 2 ) );
			if ( this.left < 0 ) this.left = 0;
                         
            $("p#vtip").css("top", this.top+"px").css("left", this.left+"px");
        }
    );
    
};
//vtip end

//share button popup
function sharePopup(linkUrl, className)
{
	var moduleWidth = 0;
	var moduleHeight = 0;
	moduleWidth = $(className).outerWidth();
	moduleHeight = $(className).outerHeight();
	
	alert( "to publish this module in your page just copy and past this code:\n<iframe width='"+ moduleWidth +"' height='"+ moduleHeight +"' src='" + linkUrl + "' scrolling='no' frameborder='0'></iframe>" );
	
}
//share button popup end


//window management
function reloadOpener( newUrl )
{
	if ( opener && typeof opener.document != undefined ) 
	{
		if ( newUrl != undefined && newUrl != "" )
		{
			window.opener.location.href = newUrl;
		}
		else
		{
			window.opener.location.href = window.opener.location.href;
		}
	}
}

function closeMe()
{
	window.open('', '_self', ''); //questa è una vaccata che serve per firefox e chrome, che non permettono di chiudere una finestra o tab che non sia stata aperta da un opener. ma in effetti sul mio firefox non funziona...
	window.close();
	//se niente ha funzionato, e la mia finestra è ancora aperta, redirigo sulla homepage almeno
	window.opener.location.href = "index.php";
}

//sostituisce un valore nella querystring
function replaceQueryString(url,param,value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
    if (url.match(re))
        return url.replace(re,'$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
}





/* jquery plugins */

//plugin for text measurement
$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>'
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

// VERTICALLY ALIGN FUNCTION
$.fn.vAlignMiddle = function() {
	return this.each(function(i){
		var ah = $(this).height();
		var ph = $(this).parent().height();
		var mh = Math.ceil((ph-ah) / 2);
		$(this).css('margin-top', mh);
	});
};
$.fn.vAlignBottom = function() {
	return this.each(function(i){
		var ah = $(this).height();
		var ph = $(this).parent().height();
		var mh = Math.ceil(ph-ah);
		$(this).css('margin-top', mh);
	});
};

//php like strip_tags
$.fn.stripTags = function() { return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') ); };



















/* THEN THINGS TO DO ON READY */


$(document).ready(
	function()
	{
		
		//activate all popup for images
		$(".popupImage").ceebox({titles:false,margin:"20",padding:"10"});
		//activate all popup for flash
		$(".popupFlash").ceebox({titles:false,margin:"20",padding:"10"});
		
		
		/*
		//activate fading links
		$("a").fadeTo("slow", 0.7); // This sets the opacity of the thumbs to fade down to 60% when the page loads
		$("a").hover(function(){
			$(this).fadeTo(500, 1.0); // This should set the opacity to 100% on hover
		},function(){
			$(this).fadeTo(1500, 0.7); // This should set the opacity to 100% on hover
		});		
		*/
		
		//activate vtips (animated tooltips)
		vtip(); 
		
		//activate jquery togglers
		//Hide (Collapse) the toggle containers on load
		$(".toggle_container").hide(); 
		$(".toggle_trigger").show();
		//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
		$(".toggle_trigger").click(function(){
			//$(this).toggleClass("active").next().slideToggle("slow");
			$(this).toggleClass("active").next().show();
			$(this).toggleClass("active").hide();
			return false; //Prevent the browser jump to the link anchor
		});
		$(".toggle_container").click(function(){
			$(this).toggleClass("active").hide();
			$(this).toggleClass("active").prev().show();
			return false; //Prevent the browser jump to the link anchor
		});
		
		//set draggable&droppable elements
		$( ".draggableDiv" ).draggable();
		$( ".droppableDiv" ).droppable({
			hoverClass: "adminDivSelected",
			greedy: true,
			tolerance: "pointer",
			activate: function( event, ui ) {
				ui.draggable.css({ 'z-index': '9999' });//cmq non va... oppure lo imposta ma cmq il div resta sotto agli altri
			},
			drop: function( event, ui ) {
				var newFatherId = this.id;
				var myId = ui.draggable.attr("id");
				var oldFatherId = $('#'+myId).data('father_div_id');
				if ( oldFatherId != newFatherId.substring(3) )
				{
					//qui sposto il div
					//e al ritorno da json ricarico la pagina
					//moveDiv($div, $oldFather, $newFather) 
					//$.getJSON('amfphp/json.php/core.Div.moveDiv/'+myId+"/"+oldFatherId+"/"+newFatherId, function(data) { initST( data ) });
					//alert("muoverei "+myId.substring(3)+" da "+oldFatherId+" a "+newFatherId.substring(3) );
					$.getJSON('amfphp/json.php/core.Div.moveDiv/'+myId.substring(3)+"/"+oldFatherId+"/"+newFatherId.substring(3), function(data) { window.location.href = window.location.href });
				}
				else
				{
					//ho cercato di spostare un div dentro a suo padre (cioè non l'ho spostato), non faccio nulla
					//window.location.href = window.location.href;
				}
			}
		});
		
		
	}
);

	
	
	
//FINALLY THINGS TO DO ON LOAD (AFTER ALL IMAGES ARE LOADED)

	
$(window).load(
	function()
	{
		//activate masonry
		$('.masonry').masonry({	animate: true }); //questo è quello in produzione
		$('.masonry').masonry({	animate: true }); //va richiamato due volte altrimenti sbaglia
		//$('.masonry').masonry({	animate: true, columnWidth: 112 }); //esempio
		//$('.moduleBox').masonry({	animate: true }); //esempio
		
	}
);
	


