var i = 0; 
var tempid='';
var disableSwitchPage = false;

function animatePic(id, classss) {  
  if (tempid!=id){
      tempid=id;
      i=0;
  }
  i = (i + 1) % 2; 
  if (i == 1) {
  	
    document.getElementById(id).className=classss+' selected';  
  } else { 
    document.getElementById(id).className=classss;   
  }
  
  if (tempid!='menu1'){
      document.getElementById('menu1').className='left';
  }
  
  if (tempid!='menu2'){
      document.getElementById('menu2').className='center';
  }
  
  if (tempid!='menu3'){
      document.getElementById('menu3').className='center';
  }
  
  if (tempid!='menu4'){
      document.getElementById('menu4').className='right';
  }
  
 } 
 
 
    //switchPages('home', 'menu1', 'left');
    
	function switchPages(page, id, classss){
        
		if(!disableSwitchPage){
			disableSwitchPage = true;
			
			//$("body").append('<div id="centerLoading" class="centerLoading"><img src="images/load_03.png" alt="loading" /> <br /> Loading</div>');
         	$.ajax({
          		url: 'templates/iPhone/'+page+".php",
          		cache: false,
          		success: function(html){
            		
					$("#content").slideUp('slow', function () {
               	     	$("#content").html('');
                    	$("#content").html(html);
                    	animatePic(id, classss);
            		});
            	
            		$("#content").slideDown('slow', function () {
                		//$("#centerLoading").remove();
						disableSwitchPage = false;
					});
            		switchListCheck=0;
          		}
        	});
		}
    }
    
    
var switchListCheck=0;
function switchListTo(id, addToBreadcrumb){
    $("ul").hide('slow');
    $("#"+id).show('slow');
    
	var breadCrumbName = $("#"+id).attr('rel');
	
    var breadCrumb;
    var title;
    if (switchListCheck == 0){
       breadCrumb='<a href="#" onclick="switchListTo(\'home\', 5);">Home</a>';
       title='Scegli la provincia';
    } else {
        breadCrumb='';
        title='Scegli tra <a href="#">tutti</a> - <b>solo aperti il 6/9/2009</b>';
    }
    if (addToBreadcrumb == 1) breadCrumb=breadCrumb+'<span id="breadcrumbItem'+id+'"> > <a href="#" onclick="switchListTo(\''+id+'\', '+switchListCheck+2+')">'+breadCrumbName+'</a></span>';
    else if (addToBreadcrumb > 1){
        switchListCheck=addToBreadcrumb;
        if (switchListCheck == 2){
            switchListCheck=0;
            $('#negoziBreadcrumb').html('<a href="#" onclick="switchListTo(\'home\', 5);">Home</a> > <a href="#" onclick="switchListTo(\''+id+'\', '+switchListCheck+2+')">'+breadCrumbName+'</a>');
            title='Scegli la provincia';
        }  else if (switchListCheck == 5){
            switchListCheck=0;
            $('#negoziBreadcrumb').html('');
            title='Scegli la regione';
        }
    }
    
    if (addToBreadcrumb != 5) switchListCheck++;
    
    $("#negoziBreadcrumb").append(breadCrumb);
    $("#topNegozi").html(title);
    
}

function showOfferte(id){
    if (id){
        $("#offerteSearchDiv").slideUp('slow', function (){
            $("#offerteDiv").slideDown('slow');
        });
        
    } else {
        $("#offerteDiv").slideUp('slow', function(){
            $("#offerteSearchDiv").slideDown('slow');
        });
        
        
    }
}

function showBlog(id){
    if (id){
        $("#blogsDiv").slideUp('slow', function (){
            $("#blogDiv").slideDown('slow');
        });
        
    } else {
        $("#blogDiv").slideUp('slow', function(){
            $("#blogsDiv").slideDown('slow');
        });
    }
} 





function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60; // * 60 * 24
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function do_geocode() {
	$( "#dialog-modal" ).dialog({
		height: 140,
		modal: true
	});
	
	var geocoder = new google.maps.Geocoder();
	
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(function(position) {  
			latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			if(geocoder){
				geocoder.geocode( { 'location': latLng}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) { 
						//alert('asd');
						//console.log(results);
						//formatted_address
						//var value = results[0].address_components[1].long_name+', '+results[0].address_components[0].long_name+', '+results[0].address_components[2].long_name+'|'+results[0].geometry.location.lat()+'|'+results[0].geometry.location.lng();
						var value = results[0].formatted_address+'|'+results[0].geometry.location.lat()+'|'+results[0].geometry.location.lng();
						Set_Cookie('geoultimoprezzo', value, 20, '/', SERVER_NAME, '');
						
						location.reload(true);
					}
				});
			}
		}, function () {
			$( "#dialog-modal" ).dialog('close');
		});
	}
	
	return false;
}

$('div').live('pageshow', function () {
	$('.ui-page-active .login').append($('#login-content'));
	$('.ui-page-active .ricalcola-container').append($('#ricalcola'));
});


var axura = {
    ver: 0.1
};
axura.uility = {};
axura.uility.isValidMail = function (mail) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(mail);
}
axura.fn = {};
/*UI*/
axura.UI = {};
/*BLOCK UI*/
axura.UI.block = function () {
    this.elBlockUI = $('#blockUI');
    if (this.elBlockUI.length == 0) {
        this.elBlockUI = $("<div/>").attr("id", "blockUI").html("").css({
            background: 'black',
            position: 'fixed',
            height: '100%',
            width: '100%',
            left: 0,
            top: 0,
            opacity: 0.5,
            'z-index': 1000,
            display: 'none'
        })

        $(document.body).append(this.elBlockUI);
    }
    this.elBlockUI.fadeIn('slow')
    this.isBlocked = true;
}
/*UNBLOCK UI*/
axura.UI.unblock = function () {
    if (this.isBlocked) {
        this.elBlockUI.fadeOut()
        this.isBlocked = false;
    }
}

/*setscope*/							
Function.prototype.setScope = function (scope) {
    var myf = this;

    return function () {
        myf.apply(scope);
    }
}

/*document.write = function (str) {
	if ($('.ui-page-active .banner').length > 0) {
		$('.ui-page-active .banner').append(str);
	} else {
		$('.banner').append(str);
	}
}*/

window.addEventListener('load', setOrientation, false);
window.addEventListener('orientationchange', setOrientation, false);

window.addEventListener('load', function(){
setTimeout(scrollTo, 0, 0, 1);
}, false);

function setOrientation() {
	var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait';  
	var cl = document.body.className;  
	cl = cl.replace(/portrait|landscape/, orient);  
	document.body.className = cl;
}

$(function () {
	$('.menu-opener').click(function () {
		$('#menu').slideToggle();
		
		$('.menu-opener').toggleClass('opened');
		
		return false;
	});

	$('input[type=radio]').each(function () {
		if ($(this).attr('checked')) {
			$(this).closest('li').addClass('checked');
		}
	});
	
	$('.radiolist label').click(function () {
		var input = $(this).closest('li').find('input');
		
		input.closest('ul').find('input[type=radio]').attr('checked', false);
		input.attr('checked', true);
		input.closest('ul').find('li').removeClass('checked');
		input.closest('li').addClass('checked');
	});

	setLoadEvent();
	/*
	Codice per autocaricare le righe allo scroll, interferisce con la pubblicitˆ
	var w = $(window);
		
	w.scroll(function () {
		if ($('#load').length > 0 && (w.scrollTop() + w.height()) > $('#load').offset().top) {
			loadRows();
		}
	});
	*/
});

var loading = false;

function loadRows() {
	if (!loading) {
		loading = true;
		
		var li = $('#load');
		var ul = li.parent();
		var offset = ul.find('li').length - 1;
		
		li.find('a').css('text-align', 'center').html('<img src="images/ajax-loader.gif" alt="" />');
		
		$.get(location.href, {
			offset: offset
		}, function (data) {
			li.remove();
			
			ul.append(data);
			
			loading = false;
		});
	}
}

function setLoadEvent() {
	$('#load').click(function () {
		loadRows();
		
		return false;
	});
}
