var GTDirectory = {
    setAjaxLink:function(el){
	if($$(el)){
	    $$(el).each(function(anchor){
		if(!anchor.href.contains("tmpl=component")){
		    if(anchor.href.contains("?")){
			anchor.href += '&tmpl=component';
		    }
		    else{
			anchor.href += '?tmpl=component';
		    }
		}
	    });
	}
    },

    destroyFormTip:function (tipClass){
	if(!tipClass)
	    tipClass = '.fc-tbx';
	$$(tipClass).each(function(el){
	    el.destroy();
	});
    },

    toggle:function(toggle, element) {
	if($(toggle) && $(element)){
	    var myMenu= new Fx.Slide(element);
	    myMenu.hide();
	    $(toggle).addEvent('click', function(e){
		e = new Event(e);
		myMenu.toggle();
		$(toggle).toggleClass('open');
		$(toggle).toggleClass('close');
		e.stop();
	    });
	}
    },
    
    loadFirstTimeVideo:function(url, control, content){
	if($(control)){
	    if($(control).value==0){
		GTDirectory.Ajax.RequestHtml(url, content);
		$(control).setAttribute("autocomplete", "off");
		$(control).value = 1;
	    }
	}
    },
    rollOver:function(id,img){
	if (id && img){
	    $(id).src=img;
	}
    },

    preloadImg:function() {
	if (!document.images) return;
	var imgs = new Array();
	var arguments = this.arguments;
	if(arguments)
	    for (var i = 0; i < arguments.length; i++) {
		imgs[i] = new Image();
		imgs[i].src = arguments[i];
	    }
    }
};
/*
GTDirectory.Map = {

    to_htmls: '',
    from_htmls:'',
    marker:'',
    directions:null,

    

    


}
 */
GTDirectory.Map = new Class({
    Implements: [Options,Events],

    options:{
	varname:'',
	mapId:'',
	lat: 0,
	lng: 0,
	txt: '',
	simply:false,
	lbl_directions:'Direzione',
	lbl_fromHere:'Parti da qui',
	lbl_toHere:'Arriva qui',
	lbl_startAddress:'Indirizzo di partenza',
	lbl_endAddress:'Indirizzo di destinazione',
	lbl_getDirections:'Ottieni indicazioni',
	lbl_walk:'A piedi',
	lbl_highways:'Evita autostrade'

    },

    initialize:function(options){
	this.setOptions(options);
	if (GBrowserIsCompatible() && $(this.options.mapId)) {
	    this.map = new GMap2($(this.options.mapId));
	    this.createMarker();

	    if(!this.options.simply){
		this.map.addControl(new GSmallMapControl());
		this.map.setCenter(new GLatLng(this.options.lat, this.options.lng), 5);
		this.map.addOverlay(this.marker);
		GEvent.trigger(this.marker, 'click');
		
	    }else{
		this.map.disableDragging();
		this.map.setCenter(new GLatLng(this.options.lat, this.options.lng), 6);
		this.map.addOverlay(this.marker);
	    }
	    
	    this.directions = new GDirections(this.map);
	    GEvent.addListener(this.directions, "error", function (){
		console.log(this.directions.getStatus().code);
	    }.bind(this));
	    this.directions.load();
	}
    },

    createMarker:function(){
	var point = new GLatLng(this.options.lat, this.options.lng);
	this.marker = new GMarker(point);
	
	if(!this.options.simply){
	   
	    var html = this.options.txt + '<br/>' + this.options.lbl_directions + ': <a href="#" id="aGMapToHere">' + this.options.lbl_toHere + '</a> - <a href="#" id="aGMapFromHere" >' + this.options.lbl_fromHere + '</a>';
	    GEvent.addListener(this.marker, "click", function() {
		this.marker.openInfoWindowHtml(html, {
		    onOpenFn:function(){
			window.addEvent('domready', function(){
			    if($('aGMapToHere')){
				$('aGMapToHere').addEvent('click', function(e){
				    e.stop();
				    this.toHere();
				}.bind(this));
			    }
			    if($('aGMapFromHere')){
				$('aGMapFromHere').addEvent('click', function(e){
				    e.stop();
				    this.fromHere();
				}.bind(this));
			    }
			}.bind(this));
		    }.bind(this)
		});
	    }.bind(this));
	}
    },

    getDirections:function(){
	var opts = {};
	if ($("walk").checked) {
	    opts.travelMode = G_TRAVEL_MODE_WALKING;
	}
	if ($("highways").checked) {
	    opts.avoidHighways = true;
	}

	var saddr = $("saddr").value
	var daddr = $("daddr").value
	alert("from: " + saddr + " to: " + daddr);
	this.directions.load("from: " + saddr + " to: " + daddr, opts);

    },

    toHere:function() {
	var toHtml = this.options.txt + '<br/>' + this.options.lbl_directions + ': <b>' + this.options.lbl_toHere + '</b> - <a href="#" id="aGMapFromHere">' + this.options.lbl_fromHere + '</a>' +
	'<br/>' + this.options.lbl_startAddress + ':<form id="formGMapFormAddress">' +
	'<input type="text" class="inputbox map_address" name="saddr" id="saddr" value="" /><br/>' +
	'<input value="' + this.options.lbl_getDirections + '" class="button map_button" type="submit"><br/>' +
	this.options.lbl_walk +' <input type="checkbox" name="walk" class="inputbox map_walk" id="walk" /> ' + this.options.lbl_highways + ' <input type="checkbox" class="inputbox map_highways" name="highways" id="highways" />' +
	'<input type="hidden" id="daddr" value="'+name+"@"+ this.options.lat + ',' + this.options.lng + '"/></form>';

	this.marker.openInfoWindowHtml(toHtml,{
	    onOpenFn:function(){
		window.addEvent('domready', function(){
		    if($('aGMapFromHere')){
			$('aGMapFromHere').addEvent('click', function(e){
			    e.stop();
			    this.fromHere();
			}.bind(this));
		    }
		    if($('formGMapFormAddress')){
			$('formGMapFormAddress').addEvent('submit', function(e){
			    e.stop();
			    this.getDirections();
			}.bind(this));
		    }
		}.bind(this));
	    }.bind(this)
	});
    },

    fromHere:function() {
	var fromHtml = this.options.txt + '<br/>' + this.options.lbl_directions + ': <a href="#" id="aGMapToHere">' + this.options.lbl_toHere + '</a> - <b>' + this.options.lbl_fromHere + '</b>' +
	'<br/>' + this.options.lbl_endAddress + ':<form id="formGMapFormAddress">' +
	'<input type="text" class="inputbox map_address" name="daddr" id="daddr" value=""/><br/>' +
	'<input value="'+this.options.lbl_getDirections+'" class="button map_button" type="submit"><br/>' +
	this.options.lbl_walk +' <input type="checkbox" name="walk" class="inputbox map_walk" id="walk" /> ' + this.options.lbl_highways + ' <input type="checkbox" class="inputbox map_highways" name="highways" id="highways" />' +
	'<input type="hidden" id="saddr" value="'+name+"@"+ this.options.lat + ',' + this.options.lng + '"/></form>';
	this.marker.openInfoWindowHtml(fromHtml,{
	    onOpenFn:function(){
		window.addEvent('domready', function(){
		    if($('aGMapToHere')){
			$('aGMapToHere').addEvent('click', function(e){
			    e.stop();
			    this.toHere();
			}.bind(this));
		    }
		    if($('formGMapFormAddress')){
			$('formGMapFormAddress').addEvent('submit', function(e){
			    e.stop();
			    this.getDirections();
			}.bind(this));
		    }
		}.bind(this));
	    }.bind(this)
	});
    }
});

GTDirectory.Map.Simple = new Class({

    initialize:function(mId, lat, lng, notSetMarker){
	if (GBrowserIsCompatible()) {
	    this.map = new GMap2($(mId));

	    this.map.addControl(new GSmallMapControl()); // added
	    this.map.setCenter(new GLatLng(lat, lng), 5);
	    var point = new GLatLng(lat, lng);
	    
	    if(!notSetMarker){
		this.placeMarker(lat, lng);
	    }else{
		var marker = new GMarker(point);
		this.map.addOverlay(marker);
	    }
	}
    },

    placeMarker:function(setLat, setLon) {

	this.map.addControl(new GSmallMapControl()); // added
	this.map.setCenter(new GLatLng(setLat, setLon), 4);
	var point = new GLatLng(setLat, setLon);
	var marker = new GMarker(point)
	this.map.addOverlay(marker);
	lastOverlay = marker;
	GEvent.addListener(this.map, 'click', function(overlay, point) {
	    if (overlay) {
		this.map.removeOverlay(overlay);
	    } else if (point) {
		if (lastOverlay){
		    this.map.removeOverlay(lastOverlay)
		}
		var marker = new GMarker(point);
		this.map.addOverlay(marker);
		this.map.panTo(point);


		var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( point );
		if ( matchll ) {
		    var lat = parseFloat( matchll[1] );
		    var lon = parseFloat( matchll[2] );
		    lat = lat.toFixed(6);
		    lon = lon.toFixed(6);
		}

		$("lat").value = lat;
		$("lng").value = lon;
		setLat = lat;
		setLon = lon;

	    }
	    lastOverlay = marker;
	}.bind(this));

    }
});

GTDirectory.Ajax = {
    evalScript:function(r, a){

	sScript = '$LAB.setOptions({AlwaysPreserveOrder: true, AllowDuplicates:false})';
	
	a.response.text.replace(/<script.*src\s*=\s*"\s*([^"]+)\s*"\s*>.*<\/script>/gi, function(){
	    sScript += ".script('" + arguments[1] + "')";
	});

	a.response.text.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
	    sScript += ".wait(function(){"+arguments[1]+"})";
	});

	sScript +=";";

	eval(sScript);
    },

    evalCss:function(r, a){
	cHtml = $$('html').get('html');
	cHtml = cHtml.toString();
	var css = new Array();

	cHtml.replace(/<link.*(?:type\s*=\s*"\s*text\/css\s*")?.*href\s*=\s*"\s*([^"]+)\s*".*(?:type\s*=\s*"\s*text\/css\s*")?\s*\/?>/gi, function(){
	    css.include(arguments[1]);
	});

	a.response.text.replace(/<link.*(?:type\s*=\s*"\s*text\/css\s*")?.*href\s*=\s*"\s*([^"]+)\s*".*(?:type\s*=\s*"\s*text\/css\s*")?\s*\/?>/gi, function(){
	    if(!css.contains(arguments[1])){
		Asset.css(arguments[1]);
	    }
	});
    },

    linkToAjax:function(el, responseContent){
	if($$(el)){
	    $$(el).each(function(anchor){
		anchor.addEvent('click', function(e){
		    e.stop();
		    new GTDirectory.Ajax.RequestHtml(anchor.href, responseContent)
		});
	    });
	}
    },

    RequestHtml:function(url, responseContent, data){
	var zIndex = 5000;
	if($('sbox-window'))
	    zIndex = $('sbox-window').getStyle('z-index') + 2;
	    
	var overlay = new GTDirectory.Ajax.Overlay(responseContent,{
	    id: 'overlay',
	    color: '#fefefe',
	    duration: 300,
	    opacity: 0.4,
	    zIndex: zIndex,
	    onClick: function() {},
	    onShow: function() {}
	});
	
	var req = new Request.HTML({
	    url: url,
	    append: responseContent,
	    noCache: true,
	    data: data,
	    onRequest: function(){
		overlay.open();
	    },

	    onComplete: function(tree, elements, html, javascript){
		var temp = this.processHTML(html);
		document.id(responseContent).empty().adopt(temp.getChildren());
		$exec(javascript);
		overlay.close();
	    }
	}).send();
    },

    SendForm:function(form, responseContent, button, action){
	if($(form)){
	    $(form).addEvent('submit', function(e){
		if(e)
		    e.stop();

		if(!action)
		    action = $(form).action

		GTDirectory.Ajax.RequestHtml(action, responseContent, $(form));
	    });

	    if($(button)){
		$(button).addEvent('click', function(e){
		    $(form).fireEvent('submit');
		});
	    }
	}
    }

};

GTDirectory.Ajax.PopulateInput = new Class({
    Implements: [Options, Events],

    options:{
	contentIds:[],
	skipElement:[],
	//selectIds:[],
	url:null,
	event: 'change',
	
	onSuccess : $empty,
	onComplete : $empty,
	onBeginStart : $empty
    },

    initialize:function(id, options, data){
	this.setOptions(options);
	this.bound = {
	    start: this.start.bind(this)
	};
	this.id = id;
	this.data = data;

	if($(id)){
	    if(this.options.event){
		$(id).addEvent(this.options.event,function(){
		    this.start();
		}.bind(this));
	    }else{
		this.start();
	    }
	}
    },

    start:function(){
	this.fireEvent('onBeginStart');
	i = 1;
	var dataToSend = '';
	if(this.data){
	    dataToSend = this.data;
	}else{
	    dataToSend = this.id + '=' + $(this.id).getValue();
	}
	this.options.contentIds.each(function(contentid){
	    if($(contentid)){
		$(contentid).addClass("ajax-loading");
		this['var_fx_' + i] = new Fx.Style($(contentid), "background-color", {
		    duration:2000
		});
	    }
	    i++;
	}.bind(this));
	
	var jsonRequest = new Request.JSON({
	    url: this.options.url,
	    data: this.data,
	    
	    onSuccess: function(response){
		this.fireEvent('onSuccess', response);
	    }.bind(this),
	    
	    onComplete: function(response){
		for (var input in response) {
		    if(this.options.skipElement.indexOf(input)<0){
			if($(input)){
			    if($(input).get('type') == 'select-one')
				$(input).set('html', response[input]);
			    else if($(input).get('type') == 'select-multiple'){
				$(input).set('html', response[input]);
			    }else if($(input).get('type') == 'text')
				$(input).set('value', response[input]);
			    else
				$(input).set('value', response[input]);
			}
		    }
		}
		i = 1;
		this.options.contentIds.each(function(contentid){
		    if($(contentid)){
			$(contentid).removeClass("ajax-loading");
		    }
		    i++;
		}.bind(this));
		
		this.fireEvent('onComplete', response);
	    }.bind(this)
	}).send(dataToSend);
    }
});

GTDirectory.Ajax.Populate = new Class({
    Implements: [Options, Events],

    options:{
	contentIds:[],
	skipElement:[],
	url:null,
	event: 'change',
	stopEvent: false,
	bgColorResponse: '#0e93f0',
	evalResponse: false,
	
	onSuccess : $empty,
	onComplete : $empty,
	onBeginStart : $empty
    },

    initialize:function(id, options, data){
	this.setOptions(options);
	this.bound = {
	    start: this.start.bind(this)
	};
	this.id = id;
	this.data = data;

	if($(id)){
	    if(this.options.event){
		$(id).addEvent(this.options.event,function(e){
		    if(this.options.stopEvent)
			e.stop();
		    this.start();
		}.bind(this));
	    }else{
		this.start();
	    }
	}else{
	    this.start();
	}
    },

    start:function(){
	this.fireEvent('onBeginStart');
	i = 1;
	var dataToSend = '';
	if(this.data){
	    dataToSend = this.data;
	}else if(this.id){
	    dataToSend = this.id + '=' + $(this.id).getValue();
	}
	
	var jsonRequest = new Request.JSON({
	    url: this.options.url,
	    data: this.data,
	    evalResponse: this.options.evalResponse,
	    
	    onSuccess: function(response){
		this.fireEvent('onSuccess', response);
	    }.bind(this),
	    
	    onComplete: function(response){
		execJavascript = false;
		for (var input in response) {
		    if(this.options.skipElement.indexOf(input)<0){
			if($(input)){
			    if($(input).get('tag') == 'input' || $(input).get('tag') == 'select'){
				if($(input).get('type') == 'select-one'){
				    $(input).set('html', response[input]);
				}else if($(input).get('type') == 'select-multiple'){
				    $(input).set('html', response[input]);
				}else if($(input).get('type') == 'text'){
				    $(input).set('value', response[input]);
				}else{
				    $(input).set('value', response[input]);
				}
			    }else if($(input).get('tag') == 'div'){
				$(input).set('html', response[input]);
			    }
			
			}else if(input == 'exec'){
			    execJavascript = response[input];
			}
		    }
		}
		if(execJavascript)
		    $exec(execJavascript);
		this.fireEvent('onComplete', response);
	    }.bind(this)
	}).send(dataToSend);
    }
});

GTDirectory.Ajax.Save = new Class({
    Implements: [Options,Events],

    options:  {
	overlay: null,
	colorOverlay: '#fefefe',
	opacityOverlay: 0.4,
	update:null,
	requestUrl:null,
	requestContent:null
    /*
	onSuccess: &empty
	 */
    },

    initialize: function(form, options) {
	this.setOptions(options);
	
	var opt = this.options;
	var zIndex = 5000;

	if($('sbox-window'))
	    zIndex = $('sbox-window').getStyle('z-index') + 2;

	var ajaxFormcheck = new FormCheck(form, {
	    display : {
		showErrors : 0,
		closeTipsButton : 0,
		flashTips : 1,
		scrollToFirst: false,
		addClassErrorToField:true,
		zIndex: zIndex
	    }
	});

	$(form).addEvent('submit', function(e){
	    e.stop();
	    
	    if(!ajaxFormcheck.isFormValid()){
		return false;
	    }

	    if(opt.overlay){
		var overlay = new GTDirectory.Ajax.Overlay(opt.overlay,{
		    id: 'overlay',
		    color: opt.colorOverlay,
		    duration: 300,
		    opacity: opt.opacityOverlay,
		    onClick: function() {},
		    onShow: function() {}
		});

		overlay.open();
	    }

	    var req = new Request.HTML({
		url: $(form).action,
		data: $(form),
		
		onComplete: function(tree, elements, html, javascript){
		    var temp = req.processHTML(html);
		    document.id(opt.update).empty().adopt(temp.getChildren());
		    $exec(javascript);
	    
		    if(opt.overlay){
			overlay.close();
		    }

		    if(opt.requestUrl && opt.requestContent){
			GTDirectory.Ajax.RequestHtml(opt.requestUrl, opt.requestContent)
		    }
		    this.fireEvent('onSuccess');
		}.bind(this)
	    }).send();
	}.bind(this));
    }
});

GTDirectory.Ajax.Overlay = new Class({

    Implements: [Options,Events],

    options:  {
	id: 'overlay',
	color: '#fff',
	duration: 500,
	opacity: 0.5,
	zIndex: 5000,
	backgroundImage: '/components/com_gtdirectory/assets/images/loading.gif'
    /*,
    onClick: $empty,
    onClose: $empty,
    onHide: $empty,
    onOpen: $empty,
    onShow: $empty
	 */
    },

    initialize: function(container,options) {
	this.setOptions(options);
	this.container = $(container);
	this.containerOriginalPosition = this.container.getStyle('position');
	this.overlay = new Element('div',{
	    id: this.options.id,
	    opacity: 0,
	    autoOpen: false,
	    styles: {
		position: 'absolute',
		background: this.options.color,
		left: 0,
		top: 0,
		'z-index': this.options.zIndex
	    },
	    events: {
		click: function() {
		    this.fireEvent('click');
		}.bind(this)
	    }
	}).inject(this.container);
	if(this.options.backgroundImage){
	    document.id(this.options.id).setStyle('background-image', "url('" + this.options.backgroundImage + "')");
	    document.id(this.options.id).setStyle('background-position', '50% 50%');
	    document.id(this.options.id).setStyle('background-repeat', 'no-repeat');
	}
	this.tween = new Fx.Tween(this.overlay,{
	    duration: this.options.duration,
	    link: 'cancel',
	    property: 'opacity',
	    onStart: function() {
		var size = this.container.getScrollSize();
		this.overlay.setStyles({
		    width: size.x,
		    height: size.y
		});
	    }.bind(this),
	    onComplete: function() {
		this.fireEvent(this.overlay.get('opacity') == this.options.opacity ? 'show' : 'hide');
	    }.bind(this)
	});
	if(this.options.autoOpen)
	    this.open();
    },
    open: function() {
	this.container.setStyle('position', 'relative');
	this.fireEvent('open');
	this.tween.start(this.options.opacity);
    },
    close: function() {
	this.fireEvent('close');
	this.tween.start(0);
	if(document.id(this.options.id))
	    document.id(this.options.id).destroy();
	this.container.setStyle('position', this.containerOriginalPosition);
    },
    show:function(){
	this.fireEvent('show');
	this.tween.start(this.options.opacity);
    },
    hide:function(){
	this.fireEvent('hide');
	this.tween.start(0);
    }
});

GTDirectory.SqueezeBox = {
    setCloseButton:function(el){
	if($$(el)){
	    $$(el).each(function(btn){
		btn.addEvent('click', function(event){
		    if(parent.SqueezeBox){
			parent.SqueezeBox.close();
		    }
		    //return false per evitare che il link riporti all'href(in genere la home)
		    return false;
		});
	    });
	}
    },

    adjustChildZIndex:function(child, modal){
	$$(child).setStyle('zIndex', $$(modal).getStyle('zIndex')+2);
    },

    destroyContent:function(obj){
	$$(obj).empty();
    },

    resizeOverlay:function(el){
	size = window.getScrollSize();
	$$(el).setStyle('height', size.y);
    },

    getElementSize: function(el){
	var copy = el.clone();
	copy.setStyles({
	    opacity : 0,
	    display : '',
	    position: 'absolute',
	    bottom : 0,
	    right : 0
	});
	$$('body')[0].adopt(copy);
	var size = copy.getSize();
	copy.destroy();
	size.y += 10;
	size.x += 10;
	return size;
    },
    
    resize: function(x,y){
	if(SqueezeBox){
	    size = $('sbox-window').getComputedSize();
	    newY = size['padding-top'] + size['padding-bottom'] + size['border-top-width'] + size['border-bottom-width'] + y;
	    newX = size['padding-left'] + size['padding-right'] + size['border-left-width'] + size['border-right-width'] + x;
	    if(x && y){
		SqueezeBox.resize({
		    y:newY,
		    x:newX
		}, true);
	    }else if(x){
		SqueezeBox.resize({
		    x:newX
		}, true);
	    }else if(y){
		SqueezeBox.resize({
		    y:newY
		}, true);
	    }
	}
    }
};

GTDirectory.Stat = {
    hit: function(type, url){
	var req = new Request.HTML({
	    url: url
	}).send('type=' + type);
    }
};

String.implement({
    toElement: (function() {
	var div = new Element('div');
	return function(oEv) {
	    return div.set('html', this).getFirst().addEvents(oEv);
	}
    })()
});

