// Place your application-specific JavaScript functions and classes here

function html5fy(type,value){
	var value = value + ""; 
}

function addCodeToFunction(func,code){
    if(func == undefined)
	return code;
    else{
		return function(){
		    func();
		    code();
		}
    }
}

function change_common(val){
	if (val=='header' || val=='footer' || val=='menu' || val=='lang'){
		$('elements_common').checked = true;
		$('elements_common').setAttribute("onclick","return false")
	}else if (val=='right'){
		$('elements_common').checked = true;
		$('elements_common').setAttribute("onclick","return true")
	}else{
		$('elements_common').checked = false;
		$('elements_common').setAttribute("onclick","return true")
	}
}

function do_login(){
	$('login_form').submit();
}

function show_el(element){
	var el = $(element);
	if (el.style.display=='none'){
		el.style.display='block'
	}else{
		el.style.display='none'
	}
}

function redraw_pages(){
	$$('.pagelist').each(function(div){
		if (div.id!=""){
			var num = div.id.split("_").last();
			var line = $('line_'+num);
			var root = $('subpages_'+num);
			var childs = $$('ul#'+root.id+' li.subpage_'+num);
			if ((childs != null) && (childs.size()>1)){
				var first = childs.first().getWidth();
				var last = childs.last().getWidth();
				line.style.marginLeft = (first/2) + "px";
				line.style.marginRight = (last/2) + "px";
			}else{
				line.style.marginLeft = "0px";
				line.style.marginRight = "0px";
				line.style.display = "none";
			}
		}
	});
}

function setAltezze() {
	// Trovo l'altezza della pagina e sottraggo l'altezza di testata e lingue
	if(document.getElementById) {
		var maxHeight = document.viewport.getHeight();
		$$('.lm_top').each(function(el){
			maxHeight = maxHeight - el.getHeight();
		})
		$$('.lm_bottom').each(function(el){
			maxHeight = maxHeight - el.getHeight();
		})
		var divs = $('page').childElements();
		for(var i = 0; i < divs.length; i++) {
			divs[i].style.height = 'auto';
			if (divs[i].offsetHeight > maxHeight) {
				maxHeight = divs[i].offsetHeight;
			}
		}
		for (var i = 0; i < divs.length; i++) {
			divs[i].style.height = maxHeight + 'px';
			if (divs[i].offsetHeight > maxHeight) {
				divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
			}
		}
	}
}

function setAltezze_class(classe) {
	// Trovo l'altezza della pagina e sottraggo l'altezza di testata e lingue
	if(document.getElementById) {
		var maxHeight = 0;
		var divs = $$('.'+classe);
		for(var i = 0; i < divs.length; i++) {
			divs[i].style.height = 'auto';
			if (divs[i].offsetHeight > maxHeight) {
				maxHeight = divs[i].offsetHeight;
			}
		}
		for (var i = 0; i < divs.length; i++) {
			divs[i].style.height = maxHeight + 'px';
			if (divs[i].offsetHeight > maxHeight) {
				divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
			}
		}
	}
}


function formatdate(data){
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	
	if ((data.value.length==2 || data.value.length==5) && (keycode!=8)){
		data.value+="/"
	}
}

function changeTheme(site,theme){
	window.location.href = '/site/update_theme/'+site+'?theme='+theme
}


function getElementsByClassName(node, classname){
	var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
         if(re.test(els[i].className))a.push(els[i]);
			return a;
}

function updateLivePreview(){
	var str=document.getElementById("site_structure_id").value;
	var f = document.getElementById("liveframe");
	f.src="/admin/structure/livepreview/"+str;
}

function setTema(id,nome){
	document.getElementById('site_structure_id').value=id;
	document.getElementById('sitename').innerHTML=nome;
	var links = getElementsByClassName(document,'livepreview');
	for (var i in links){
		if (links[i].style!=undefined){
			if (links[i].id == 'tema_'+id)	
				links[i].style.display = 'inline'
			else
				links[i].style.display = 'none'
		}
	}
}

function seleziona_passo(idx){
	for(var i=0;i<=4;i++){
		(i==idx) ?
			$('home_'+i).appear() :
			$('home_'+i).hide();
	}
}

function show_theme(idx,max){
	$$('.themed_category').each(function(cat){
		(cat.id=='list_'+idx) ? 
			cat.appear() :
			cat.hide();
	});
}

function serv_unregister(site,service){
	new Ajax.Updater('check_'+service,'/application_unregister/'+service+'?site='+site, {
		asynchronous:true, 
		evalScripts:true, 
		onLoading:function(request){
			$('check_'+service).innerHTML='<img src="/images/hw/spinner.gif" />'
		} 
	});	
}

function serv_register(site,service){
	new Ajax.Updater('check_'+service,'/application_register/'+service+'?site='+site, {
		asynchronous:true, 
		evalScripts:true, 
		onLoading:function(request){
			$('check_'+service).innerHTML='<img src="/images/hw/spinner.gif" />'
		} 
	});
}

function show_page_link(){
	$('link_url').show();
}	

function hide_page_link(){
	$('link_url').hide();
}	

function show_price(){
	var out
	$$('.site_packet').each(function(el){ if (el.checked) out = el })
	id = out.value
	new Ajax.Request('/packet/price/'+id, {
		onComplete: function(transport){
			ans = eval("("+transport.responseText+")")
			if (ans["packet"]["dominio"] == 1){
				$('compra_domain').show();
				$('compra_subdomain').hide();
				$('site_title').value = '';
			}else{
				$('compra_domain').hide();
				$('compra_subdomain').show();
				$('site_domain').value = '';
			}
			$('spec_box').show();
			
			var app_price = 0.0
			$$('.site_application').each(function(el) { 
				if (el.checked) {
					app_price = app_price + $('price_' + el.id.replace('application_','')).value * 1.0
				}
			});
			ans["packet"]["price"] = ans["packet"]["price"] * 1 + app_price * 1
			new Effect.Highlight('spec_box')
			$('dominio').innerHTML = '<td style="font-weight:bold;text-align:right;width:50%;">Dominio:</td><td>' + ((ans["packet"]["dominio"] == 1) ? 'si' : 'no') + '</td>'
			$('pagine').innerHTML = '<td style="font-weight:bold;text-align:right;width:50%;">Pagine:</td><td>' + ((ans["packet"]["pagine"] == -1) ? 'Illimitate' : ans["packet"]["pagine"]) + '</td>';
			$('email').innerHTML = '<td style="font-weight:bold;text-align:right;width:50%;">Email:</td><td>' + ((ans["packet"]["email"] == -1) ? 'Illimitate' : ans["packet"]["email"]) + '</td>';
			$('webmail').innerHTML = '<td style="font-weight:bold;text-align:right;width:50%;">Webmail:</td><td>' + ((ans["packet"]["webmail"] == 1) ? 'si' : 'no') + '</td>';
			$('checkme').innerHTML = '<td style="font-weight:bold;text-align:right;width:50%;">Checkme:</td><td>' + ((ans["packet"]["checkme"] == 1) ? 'si' : 'no') + '</td>';
			$('statistic').innerHTML = '<td style="font-weight:bold;text-align:right;width:50%;">Statiche:</td><td>' + ((ans["packet"]["statistic"] == 1) ? 'si' : 'no') + '</td>';
			$('price').innerHTML = '<td style="font-weight:bold;font-size:larger;text-align:center;width:100%;" colspan="2">' + ans["packet"]["price"].toFixed(2) + ' &euro;</td>';
			if ($('title').value==''){
				$('user_info').hide();
				$('compra_info').hide();
				$('compra_send').hide();
			}
		}
	})
}

function check(field, site){
	if (field == 'domain'){
		$('site_title').value = $('site_domain').value + Math.ceil(Math.random()*100);
	}
	new Ajax.Request('/check?'+field+'='+$('site_'+field).value+'&ext='+$('site_domain_ext').value+'&base='+site, {
		onComplete: function(transport){
			ans = eval('('+transport.responseText+')');
			$('compra_msg').innerHTML = ans["message"];
			if (ans["status"]==1){
				$('user_info').show();
				$('compra_info').show();
				$('compra_send').show();
			}else{
				$('user_info').hide();
				$('compra_info').hide();
				$('compra_send').hide();
			}
			Effect.ScrollTo('user_info');
		}
	})
}

function validateGenericForm(form){
	var msg = ""
	$$('#'+form.id+' input, #'+form.id+' textarea').each (function(el){
		if (el.getAttribute("required")!=undefined){
			if (el.type=="email"){
				var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
				if (el.value.search(emailRegEx) == -1) {
					msg += "* Il campo " + el.id + " non è nel formato corretto\n";
				}
			}else if (el.value==""){
				msg += "* Il campo " + el.id +" è obbligatorio \n";
			}
		}
	});
	if (msg!=""){
		alert(msg);
		return false;
	}else{
		return true;
	}
}

window.onload = addCodeToFunction(window.onload,function() { 
	try{
		setAltezze(); 
		
		//Gestisco gli eventuali Marqee
	 	toMarqee = $$('.marqee');
	 	for(var ti = 0; ti < toMarqee.length; ti++){
	 		new verticalMarquee(toMarqee[ti].id);
		}
		
		if ($('srch_fld')!=undefined){
			new Form.Element.Observer('srch_fld', 0.5, function(element, value) {
				new Ajax.Updater('searchResults', '/admin/elements/search', {
					asynchronous:true, 
					evalScripts:true, 
					onLoaded:function(request){
						document.getElementById('busy').style.display='none'
					}, 
					onLoading:function(request){
						document.getElementById('busy').style.display='inline'
					}, 
					parameters:'criteria=' + escape(value)
				})
			})
		}
	}catch(e){
	}
});
