/**
 * Utility functions used around fotogallery project
 * @author 		Davide Debernardi
 * @package 	JS-Utils
 */
$j = jQuery.noConflict();
 TG = new Object;
 TG.debug = false;
 TGUtils = function(config){
 	this.debug = true;
	this.config = config;
	this.initialized 	= false;
	this.Void = function(){ };
	this.Debug = function(e){
		if(this.debug == true){
			document.body.innerHTML += e.name+': '+e.message+'\n<br>';
		}
 	};
	this.extend = function(destination, source){
	 	for(prop in source){
			try{
				if(destination[prop] === '' || destination[prop] === undefined){
					destination[prop] = source[prop];
				}
				var value = source[prop];
				if(typeof source[prop] == 'object'){
					value = typeof source[prop];	
				}
				//this.Debug({name: "Initializing "+ typeof destination + ' ' + prop, message: value})
			} catch(e){
				this.Debug(e)
			}
		}
		return destination;
	 }
 };
 TG.SimpleStore = function(){
 	this._idCounter = 0;
	this._getCounter = function(){
		if(undefined === this._idCounter){
			this._idCounter = 0;
		}
		var counter = this._getParam('_idCounter');
		this._setParam('_idCounter', ++counter);
		return counter;
	};
 	this._getParam = function(param){
		try{
			var app = this;
			var ret = app[param];
			return ret;
		}catch(e){
			TGUtils.prototype.Debug(e)
			return null;
		}
	}; 
	this._setParam = function(param, value){
		try{
			this[param] = value;
		} catch(e){
			TGUtils.prototype.Debug(e)
		}
		return this;
	}
 };
 TG.SimpleStore.constructor = TG.SimpleStore();
 SimpleStore = new TG.SimpleStore();
 TGUtils.constructor = TGUtils();
 TG.WBX = function(config){
 	this.defaults = {
		closePrevious: true,
		autoclose: true,
		renderToBody: false,
		iFrameContent: false,
		destination: 'default-destination',
		message: "Warning!!",
		buttons: 	[{}],
		container: 	{}
	};
	this.config = config;
 };
 TG.WBX.prototype = new TGUtils();
 TG.WBX.constructor = TG.WBX();
 TG.WBXAlert = function(config){
 	this.defaults = {
		destination: '',
		message: "Warning!!",
		buttons: 	[{text: "ok", onclick: function(){alert('è quello dell\'alert!!')}}],
		container: 	{}
	}
	this.config = config;
 }
 TG.WBXAlert.constructor = TG.WBXAlert();
 TG.WBXAlert.prototype = TG.WBX.prototype;
 
 TG.WBXConfirm = function(config){
 	this.defaults = {
		destination: 'prova',
		message: "Confermi?",
		innerHTML: '',
		buttons: 	[	{text: "ok", onclick: function(){alert('ok')}}, 
						{text: "no", onclick: function(){alert('no')}}
					],
		container: 	{}
	}
	this.config = config;
 }
 TG.WBXConfirm.constructor = TG.WBXConfirm();
 TG.WBXConfirm.prototype = TG.WBX.prototype;
 
 TG.WBX.prototype.show = function(){
 	try {
		if(this.initialized === false){
			this.init();
		}
		this.container.show(this.config.destination, this.config.renderToBody);
		this.position();
	} catch(e){
		this.Debug(e)
	}
 }
 TG.WBX.prototype.position = function(){
 	position = document.getElementById(this.config.destination).parentNode.getBoundingClientRect();
	width = (parseInt( position.right ) - parseInt( position.left));
	$j('#rep-problem').css('left', (( width - $j('#rep-problem').width())/2)+'px').css('position', 'relative');
 }
 TG.WBX.prototype.iFrameContent = function(){
 		temp = document.createElement('iframe');
		temp.setAttribute('src', this.config.iFrameContent);
		this.elements.push(temp);
 }
 
 TG.WBX.prototype.getNoIframeElements = function(){
 		temp = document.createElement('p');
		temp.className = 'bold';
		temp.style.paddingBottom = '5px';
		temp.innerHTML = this.config.message;
		this.elements.push(temp);
		temp = this.getInnerHtml();
		if(temp){
			this.elements.push(temp);
		}
/*		temp = document.createElement('br');
		this.elements.push(temp);*/
		this.config.buttons.each(function(button){
			button.autoclose = this.config.autoclose ? this.config.autoclose : undefined;
			temp = new TG.Button(button);
			temp.init(this);
			this.elements.push(temp.HTMLObject);
		}, this);
 }
 TG.WBX.prototype.init = function(){
 	try{
		this.config 	= this.extend(this.config, this.defaults)
		document.getElementById(this.config.destination).style.position = 'relative';
		try {
			this.Close();
		} catch(e){
			
		}
		this.container 	= {};
		this.elements 	= [];
		if(this.config.iFrameContent){
			this.iFrameContent();
		} else{
			this.getNoIframeElements();
		}
		
		this.container 	= new TG.WBXContainer(this.config.container);
		
		this.container.init(this.elements);
		this.initialized = true;
		SimpleStore._setParam('closePrevious', this.config.closePrevious)
		SimpleStore._setParam('destination', this.config.destination);
		try{
			if(this.config.fixlayout == true){
				SimpleStore._setParam('oldpositioning', this.config.destination.style.position);
				this.config.destination.style.position = 'relative';
			}
		} catch(e){
			//don't know if fixlayout is defined...
		}
	} catch(e){
		this.Debug(e)
	}
 }
 TG.WBX.prototype.getInnerHtml = function(){
 	try{
		target = this.config.innerHTML;
		if(target !== '' && undefined !== target){
			var element = document.getElementById(target).cloneNode(true);
			element.style.display = 'block';
			var newId = element.getAttribute('id')+SimpleStore._getCounter();
			element.setAttribute('id', newId);
			SimpleStore._setParam('innerHTML', newId);
			var temp = document.createElement('form');
			temp.setAttribute('action', ''); temp.setAttribute('method', 'POST')
			temp.appendChild(element)
			return temp;
		} return false;
	} catch(e){
		this.Debug(e);
	}
 }
 TG.WBX.prototype.Close = function(){
	try{
		if(document.getElementById('overlay') !== null && document.getElementById('overlay') !== undefined){
			document.getElementById('overlay').style.display = 'none';
			document.getElementById('overlay').setAttribute('id', 'old-overlay-'+SimpleStore._getCounter());
			document.getElementById('content_overlay').style.display = 'none';
			document.getElementById('content_overlay').setAttribute('id', 'old-content-'+SimpleStore._getCounter());
			document.getElementById('rep-problem').setAttribute('id', 'old-problem-'+SimpleStore._getCounter());
		}
	} catch(e){
		this.Debug(e);
	}
 }
 TG.Button = function(config){
 	this.defaults = {
		autoclose: true,
		text: 'ok',
		btnClass: 'button',
		onclick: function(){},
		onfocus: function(){}
	}
	this.config = config;
	this.HTMLObject = {};
 };
 TG.Button.constructor= TG.Button();
 TG.Button.prototype = new TGUtils();
 TG.Button.prototype.init = function(parent){
 	try{
		this.config 	= this.extend(this.config, this.defaults)
		if(this.initialized == false){
			this.counter = SimpleStore._getCounter();
		 	this.config = this.extend(this.config, this.defaults);
			this.HTMLObject = document.createElement('div');
			this.HTMLObject.style.cssFloat = 'left';
			this.HTMLObject.className = this.config.btnClass;
			this.HTMLCont = document.createElement('span')
			this.HTMLLink = document.createElement('a');
			this.HTMLLink.setAttribute('href', 'javascript:void(0)');
			this.HTMLLink.innerHTML = this.config.text;
			this.HTMLLink.setAttribute('counter', this.counter);
			SimpleStore._setParam('_WBXOnclick'+this.counter, this.config.onclick);
			SimpleStore._setParam('_WBXAutoclose'+this.counter, this.config.autoclose);
			this.HTMLLink.onclick = ClickAndClose;
			this.HTMLLink.onfocus = this.config.onfocus;
			this.HTMLCont.appendChild(this.HTMLLink);
			this.HTMLObject.appendChild(this.HTMLCont);
			this.initialized = true;	
		}
		return this;
	} catch(e){
		this.Debug(e);
	}
 };
 TG.WBXContainer = function(config){
 	 this.defaults = {
		innerHTML: '',
	 	innerBox: {
		 	verticalPosition: '35%',
			width: '90%'
		},
	 	style: {
		 	bgColor: 	'#FFFFFF',
		 	color: 		'#000000'
		},
		elType: 	'div',
		elClass: 	'sbianca',
		attributes: {
			id:		'sbianca'
		}
	 }
	 this.config = config;
	 this.HTMLObject = {};
	 this.HTMLMessageObject = {};
 };
 TG.WBXContainer.constructor = TG.WBX();
 TG.WBXContainer.prototype = new TGUtils();
 TG.WBXContainer.prototype.show = function(id, toBody){
 	try{
		if(toBody){
			this.OverlayObject.style.position = "fixed";
			this.OverlayContentObject.style.position = "fixed";
			this.OverlayContentObject.style.left = "40%";
			document.body.appendChild(this.OverlayObject);
			document.body.appendChild(this.OverlayContentObject);
		} else {
			destination = document.getElementById(id).parentNode
			
			this.OverlayContentObject
			destination.appendChild(this.OverlayObject);
	 		destination.appendChild(this.OverlayContentObject);
		}
//		document.getElementById('rep-problem').setAttribute('class',(document.getElementById('rep-problem').getAttribute('class')))
		return this
	}catch(e){
	 	this.Debug(e);
	}
 }
 
 TG.WBXContainer.prototype.init = function(els){
 	try{
	 	this.config = this.extend(this.config, this.defaults);		
		/** create the overlay div */
		this.OverlayObject = document.createElement('div');
		this.OverlayObject.setAttribute('id', 'overlay');
		this.OverlayObject.className = 'overlay';
		this.OverlayObject.style.visibility = 'visible';
		this.OverlayObject.innerHTML = '<!-- -->';
		/** create the content for the overlay */
		this.OverlayContentObject = document.createElement('div');
		this.OverlayContentObject.setAttribute('id', 'content_overlay');
		this.OverlayContentObject.className = 'content_overlay';
		this.OverlayContentObject.style.visibility = 'visible';
		/** create the container for both message and buttons */
		this.MessageContainerObject = document.createElement('div');
		this.MessageContainerObject.className = 'photo-problem';
		this.MessageContainerObject.setAttribute('id', 'rep-problem');
		
		els.each(function(el){
			this.MessageContainerObject.appendChild(el)
		}, this)
		
		this.OverlayContentObject.appendChild(this.MessageContainerObject);
		//this.HTMLObject.appendChild(this.HTMLMessageCont);
		this.initialized = true;
		return this;
	} catch(e){
		this.Debug(e);
	}
 };
 TG.debug = true;
 getElementByEvent = function(e){
 	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
 }
 ClickAndClose = function(evt){
  	var target = getElementByEvent(evt);
	var counter = target.getAttribute('counter');
 	func = SimpleStore._getParam('_WBXOnclick'+counter);
	autoclose = SimpleStore._getParam('_WBXAutoclose'+counter);
	try{
		window[func]();
	} catch(e){}
		
 	if (autoclose == true) {
		try{
			TG.WBX.prototype.Close();
		}  catch(e){
			alert(e.message)
		}
 	}
 }
 var refresh = function(){
 	history.go(0);
 }
 
/** 
 * Functions used to set the hidden value with id 'what' so I use the hidden field and not submit values.
 * In fact I do not have a real submit button, just links on whose clicks I can submit the form.
 */
function submitIgnore(){
	document.getElementById('what').value = "ignore";
	document.getElementById('general-form').submit();
}
function submitSave(){
	document.getElementById('what').value = "save";
	document.getElementById('general-form').submit();
}
function submitCancel(){
	document.getElementById('what').value = "cancel";
	document.getElementById('general-form').submit();
}

function toggleMessage(id, str){
	if(	document.getElementById(id).value == str){
		document.getElementById(id).value = '';
		document.getElementById(id).style.color = '#000000';
	} else if (	document.getElementById(id).value === '' 
				|| document.getElementById(id).value === 'undefined'){
		document.getElementById(id).value = str;
		document.getElementById(id).style.color = '#999999';
	}
}

function validateTitle(){
	var value 	= document.getElementById('title').value;
	if( value == '' || value === 'undefined'){
		document.getElementById('error').innerHTML = 'inserisci il titolo per il nuovo album';
		document.getElementById('error').style.display = 'block';
		return false;
	}
	document.getElementById('error').style.display = 'none';
	return true;
}

function titleFormSubmit(){
	if(validateTitle()){
		document.getElementById('general-form').submit();
	} 
	return false;
}

function toggleChild(from, to){
	if(document.getElementById(from).selected === true){
		document.getElementById(to).disabled = false;
	} else {
		document.getElementById(to).disabled = true;
	}
}
function getElementByEvent(evt){
		var targ;
		if (!evt) var evt = window.event;
		if (evt.target) targ = evt.target;
		else if (evt.srcElement) targ = evt.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;
		return targ;
	}
function getWindowSize(){
	var myWidth = 0, myHeight = 0;
	var ret = [];
	if( typeof( window.innerWidth ) == 'number' ) {
    	//Non-IE
    	myWidth = window.innerWidth;
    	myHeight = window.innerHeight;
  	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    	//IE 6+ in 'standards compliant mode'
   	 	myWidth = document.documentElement.clientWidth;
    	myHeight = document.documentElement.clientHeight;
  	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    	//IE 4 compatible
    	myWidth = document.body.clientWidth;
    	myHeight = document.body.clientHeight;
  	}
	ret['width'] = myWidth;
	ret['height'] = myHeight;
	return ret;
}
function ajaxDebug(resp){
	alert(resp.responseText)
}

function selectFocusContent(id){
	document.getElementById(id).select();
}
function deleteFoto(resp){
	document.location = resp.responseText;
}

