$(function(){
	hoverForIE6("#main-stories", "hover");
	initNavIndexes();
	clearInputs();
	initGallery();
	initNav();
	textChanger.init();
	/* box mutui/prestiti */
	if($("button, input:submit" ).length > 0) $("button, input:submit" ).button();
	$('.filter-box.mutui .buttons li:eq(0) a').click(function(){return false;});
  $('.filter-box.prestiti .buttons li:eq(1) a').click(function(){return false;});
	$('.filter-box.mutui .buttons li:eq(1) a').click(function(){
	  $('.filter-box.mutui').hide();
	  $('.filter-box.prestiti').show();	  
	  return false;
	});
  $('.filter-box.prestiti .buttons li:eq(0) a').click(function(){
    $('.filter-box.mutui').show();
    $('.filter-box.prestiti').hide();
    return false;
  });
	
	/* conteggio visite all'articolo */
  if(typeof uuid != "undefined" && typeof doctype != "undefined" && doctype == "articolo") {
    var serviceUrl="/php/piuletti/artratingsvc.php";
    var title = escape(document.title);
    var DocRulesView = 'Libero';
    var url = escape(document.URL);
    if(typeof(doctype) == "undefined") {
      doctype = "articolo";
    }
    var dataUrl = "uuid=" + uuid;
    dataUrl += "&title=" + title;
    dataUrl += "&DocRulesView=" + DocRulesView;
    dataUrl += "&type=" + doctype;
    dataUrl += "&channel=casa2011";
    dataUrl += "&url=".concat(url);
    if(uuid.length > 0 && title.length > 0) {
      $.ajax({
         type: "GET",
         url: serviceUrl,
         data:dataUrl,
         success: function(msg){
                  $(document.body).append(msg);
         }
       });
    }
  }
  $(".info .history").click(function(){$(".article-history").slideDown(250);return false;});
  $(".article-history .dismiss").click(function(event){$(".article-history").slideUp(250);return false;});
  $(".control .print").click(function(){urlDoc=window.location.pathname.split(".php")[0]+"_PRN.php";window.open(urlDoc,'anteprimaE','resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,width=645,left=200,top=200,innerWidth=640,screenX=200,screenY=200'); return false;})
  $(".control .mail").click(function(){document.location.href="mailto:?body="+escape(document.location)+"&subject="+escape(document.title)+"&"; return false;})
  $(".popular .tabs .active").click(function(){return false;});
  /* strip agora */
  $(".agora-strip .heading .tabs li a").click(function(){switchagoratab($(this).attr("rel")); return false;});
  /* webmobili */
  var arrayvalue = new Array();
  $("#cmsubmit").click(function(){
    if($("#AmbientID").val()==""
      || $("#AmbientID:not(:disabled)").val()==""
      || $("#TypeID:not(:disabled)").val()==""
      || $("#p3:not(:disabled)").val()==""
      || $("#p4:not(:disabled)").val()==""
      || $("#p5:not(:disabled)").val()==""
      ) {
      alert("Seleziona tutte le opzioni");
      return false;
    }
    $("#TypeID, #p3, #p4, #p5").removeAttr('disabled');
    sc_customLinkTracking({
        prop42: s.pageName,
        prop43: "prodotti:ricerca",
        prop44: s.pageName + " | prodotti:ricerca",
        prop45: "trovaprodotti"
    });
  });
  $(".cerca-mobili .azz").click(function(){
    $("#AmbientID").val("");
    $("#TypeID, #p3, #p4, #p5").html('<option value="">Seleziona</option>').attr("disabled","disabled");
    $("label[for='TypeID'], label[for='p3'], label[for='p4'], label[for='p5']").html("&nbsp;");
    return false;
  });     
  $("#AmbientID").change(function(){
    $("#TypeID, #p3, #p4, #p5").html('<option value="">Seleziona</option>').attr("disabled","disabled");
    $("label[for='TypeID'], label[for='p3'], label[for='p4'], label[for='p5']").html("&nbsp;");
    var output = [];
    var selectValues = combovalue[$("#AmbientID :selected").attr("rel")];
    output.push('<option value="">Seleziona</option>');
    if(selectValues){
      $.each(selectValues, function(key, value)
      {
        arrayvalue = value.split("||");
        output.push('<option value="'+ arrayvalue[0] +'" rel="'+ key +'">'+ arrayvalue[1] +'</option>');
      });    
      $('#TypeID').html(output.join(''));
    }
    if($('#TypeID option').length>1){
     $('label[for="TypeID"]').html(arrayvalue[2]);
     $('#TypeID').removeAttr('disabled');
    };
  });
  $("#TypeID").change(function(){
    $("#p3, #p4, #p5").html('<option value="">Seleziona</option>').attr("disabled","disabled");
    $("label[for='p3'], label[for='p4'], label[for='p5']").html("&nbsp;");
    var output = [];
    var selectValues = combovalue[$("#TypeID :selected").attr("rel")];
    output.push('<option value="">Seleziona</option>');
    if(selectValues){
      $.each(selectValues, function(key, value)
      {
        arrayvalue = value.split("||");
        output.push('<option value="'+ arrayvalue[0] +'" rel="'+ key +'">'+ arrayvalue[1] +'</option>');
      });     
      $('#p3').html(output.join(''));
    }
    if($('#p3 option').length>1){
     $('label[for="p3"]').html(arrayvalue[2]).removeClass("hidden2");
     $('#p3').removeAttr('disabled').removeClass("hidden2");
    };
  });
  $("#p3").change(function(){
    $("#p4, #p5").html('<option value="">Seleziona</option>').attr("disabled","disabled");
    $("label[for='p4'], label[for='p5']").html("&nbsp;");
    var output = [];   
    var selectValues = combovalue[$("#p3 :selected").attr("rel")];
    output.push('<option value="">Seleziona</option>');
    if(selectValues){
      $.each(selectValues, function(key, value)
      {
        arrayvalue = value.split("||");
        output.push('<option value="'+ arrayvalue[0] +'" rel="'+ key +'">'+ arrayvalue[1] +'</option>');
      });
      $('#p4').html(output.join(''));
    }
    if($('#p4 option').length>1){
     $('label[for="p4"]').html(arrayvalue[2]);
     $('#p4').removeAttr('disabled');
    };    
  });
  $("#p4").change(function(){
    $("#p5").html('<option value="">Seleziona</option>').attr("disabled","disabled");
    $("label[for='p5']").html("&nbsp;");
    var output = [];   
    var selectValues = combovalue[$("#p4 :selected").attr("rel")];
    output.push('<option value="">Seleziona</option>');
    if(selectValues){
      $.each(selectValues, function(key, value)
      {
        arrayvalue = value.split("||");
        output.push('<option value="'+ arrayvalue[0] +'" rel="'+ key +'">'+ arrayvalue[1] +'</option>');
      });    
      $('#p5').html(output.join(''));
    }
    if($('#p5 option').length>1){
      $('label[for="p5"]').html(arrayvalue[2]);
      $('#p5').removeAttr('disabled');
    };
  });  
});

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: 'div.overflower',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.btn-prev',
		btnNext:'a.btn-next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:'div.switcher div.holder',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:700,
		easing:'swing',
		event:'click',
		afterInit:false,
		vertical:false,
		step:false
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;

		// gallery init
		if(!_slides.length) return;
		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=$(this).outerWidth(true);
			_sumHeight+=$(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = $('<ul />');
			for(var i=0; i<_stepCount; i++) $('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			//if(_btnPrev.hasClass(_disabledClass)) return;
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			//if(_btnNext.hasClass(_disabledClass)) return;
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function switchSlide() {
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
}


function switchagoratab(tab){
  var reload = new Date().getTime();
  var tabsurl = new Array();
  tabsurl["tuttoagora"]       =  "/includes2010/external/tuttoagora.php";
  tabsurl["agoracasaecase"]   =  "/includes2010/external/agoracasaecase.php";
  tabsurl["agoranido"]        =  "/includes2010/external/agoranido.php";
  tabsurl["opinioni"]         =  "/includes2010/methode/agora/opinioni.html";
  tabsurl["casaecase"]        =  "/includes2010/methode/agora/casaecase.html";
  tabsurl["mondoimmobiliare"] =  "/includes2010/methode/agora/mondoimmobiliare.html";
  $(".agora-strip .heading .tabs li a").removeClass("active");
  $(".agora-strip .heading .tabs li a[rel='"+tab+"']").addClass("active");
  $('.agora-strip .overflower').load(tabsurl[tab]+'?r='+reload, function() {initGallery();});  
}

function initGallery(){
  $('.switcher .holder').html("");
	if($('div.house-gallery, div.gallery-place').length > 0) $('div.house-gallery, div.gallery-place').scrollGallery({circleSlide:false});
	if($('div.mesi, div.anni').length > 0) $('div.mesi, div.anni').scrollGallery({
	  btnPrev:'a.arrow-left',
    btnNext:'a.arrow-right',
    sliderHolder: 'div.slider',
    slider: 'div.overflower > ul'
  });
	if($('#main-stories').length > 0) $('#main-stories').scrollGallery({
		generatePagination:'div.pager div.frame',
		duration:1,
		autoRotation:true
	});
	if($('div.gallery').length > 0) $('div.gallery').scrollGallery({
		sliderHolder: 'div.slider',
		slider: 'div.overflower > ul'
	});
	if($('div.gallery-foto').length > 0) $('div.gallery-foto').scrollGallery({
    sliderHolder: 'div.slider',
    slider: 'div.overflower',
    slides: '>a',
    btnPrev:'a.ar-up',
    btnNext:'a.ar-down',
    circleSlide:false,
    vertical:true,
    disabledClass:'disabled'
  });
}

function initNav(){
	if ($.browser.msie && $.browser.version < 7) {
		$('#nav>li').each(function(){
			var $this = $(this);
			var drop = $('div.drop-down',$this).get(0);
			$this.mouseenter(function(){
				$this.addClass('hover');
				hideSelectBoxes(drop)
			}).mouseleave(function(){
				$this.removeClass('hover');
				showSelectBoxes(drop);
			});
		});
	}
}

var textChanger = {
	cpanel : '#textchanger',  //set here the id of the element (div, p) within you want to insert the control panel
	element : '#resize-text > p',   	 //set here the id of the element (div, p) within you want to change the text
	defaultFS : 15,         //set here the default font size in 'px'
	init: function() {
		var cpel = $(textChanger.cpanel);
		var el = $(textChanger.element);
		if (cpel == null || el == null) {return} else {
  		var sz = textChanger.getCookie();
  		el.css("font-size", sz ? sz + 'px' : textChanger.defaultFS + 'px');
  		$('#increase').click(function(){
  		  var el = $(textChanger.element);
  		  var fSize = parseFloat(el.css("font-size"));
        fSize += 1;
        if (fSize > 18) fSize = 18;
    		el.css("font-size", fSize+'px');
        textChanger.updateCookie(fSize);
        return false;
  		});
  		$('#decrease').click(function(){
  		  var el = $(textChanger.element);
  		  var fSize = parseFloat(el.css("font-size"));
        fSize -= 1;
        if (fSize < 9) fSize = 9;
    		el.css("font-size", fSize+'px');   
        textChanger.updateCookie(fSize);
        return false;
  		});		
		}
	} ,
		
	updateCookie: function(vl) {
		var today = new Date();
		var exp = new Date(today.getTime() + (365*24*60*60*1000)); //the cookie will expire in one year  
		document.cookie = 'textChangerL=size=' + vl + ';' +'expires=' + exp.toGMTString() + ';' +'path=/';
	} ,

	getCookie: function() { 
		var cname = 'textChangerL=size=';	
		var start = document.cookie.indexOf(cname);
		var len = start + cname.length;
		if ((!start) && (cname != document.cookie.substring(0,cname.length))) {return null;}
		if (start == -1) return null;
		var end = document.cookie.indexOf(";",len);
		if (end == -1) end = document.cookie.length;
		return unescape(document.cookie.substring(len, end));
	}
}

function hideSelectBoxes(object)
{
	if (!object) return;
	if (!object.sboxes)
		object.sboxes = [];
	var ol = getElementX(object);
	var ot = getElementY(object);
	var ow = object.offsetWidth;
	var oh = object.offsetHeight;
	var sboxes = document.all.tags("select");
	for (var i=0; i<sboxes.length; i++)
	{
		var node = sboxes[i].parentNode;
		while (node != object && node.tagName != "BODY")
			node = node.parentNode;
		var skip = (node == object);
		if (skip) continue;
		var t = getElementY(sboxes[i]);
		var l = getElementX(sboxes[i]);
		var w = sboxes[i].offsetWidth;
		var h = sboxes[i].offsetHeight;
		var ver = false;
		if (t > ot && t < (ot + oh))
			ver = true;
		else if ((t + h) > ot && (t + h) < (ot + oh))
			ver = true;
		var hor = false;
		if (l > ol && l < (ol + ow))
			hor = true;
		else if ((l + w) > ol && (l + w) < (ol + ow))
			hor = true;
		else if (l < ol && (l + w) > ol)
			hor = true;
		if (ver && hor && sboxes[i].style.visibility != "hidden")
			object.sboxes[object.sboxes.length] = sboxes[i];
	}
	for (var i=0; i<object.sboxes.length; i++)
		object.sboxes[i].style.visibility = "hidden";
}

function showSelectBoxes(object)
{
	if (!object) return;
	if (!object.sboxes) return;
	for (var i=0; i<object.sboxes.length; i++)
		object.sboxes[i].style.visibility = "";
	object.sboxes = [];
}

function getElementX(object) {return getElementC(object, true)}
function getElementY(object) {return getElementC(object, false)}

function getElementC(element, xAxis)
{
	var initialElement = element;
	var c = 0;

	while (element != null)
	{
		c += (xAxis) ? element.offsetLeft : element.offsetTop;
		if (element.style.position == "absolute")
			break;
		else
			element = element.offsetParent;
	}

	var elementWnd = document.window;
	if (!elementWnd) return c;

	if (!elementWnd.frameElement) return c;

	return c + getElementC(elementWnd.frameElement, xAxis);
}

//ie6 hover
function hoverForIE6(h_list, h_class){
	if($.browser.msie && $.browser.version < 7){
		if(!h_class) var h_class = 'hover';
		$(h_list).mouseenter(function(){
			$(this).addClass(h_class);
		}).mouseleave(function(){
			$(this).removeClass(h_class);
		});
	}
}

/*---- clear inputs ---*/
function clearInputs(){
	$('input:text, input:password, textarea').each(function(){
		var _el = $(this);
		var _val = _el.val();
		_el.bind('focus', function(){
			if(this.value == _val) this.value = '';
		}).bind('blur', function(){
			if(this.value == '') this.value = _val;
		});
	});
}

function initNavIndexes()
{
	var nav = document.getElementById("breadcrumbs");
	if(nav) {
		var lis = nav.getElementsByTagName("li");
		for (var i=0; i<lis.length; i++) {
			lis[i].style.zIndex = lis.length-i;
		}
	}
}


function c24share(tipo) {
  var title = encodeURIComponent(document.title);
  var url = encodeURIComponent(document.URL);
  switch(tipo){
    case "facebook":
      window.open('http://www.facebook.com/sharer.php?&u='+url+'&t='+title);
    break;
    case "twitter":
      window.open('http://twitter.com/home?status='+title+':+'+url);
    break;
    case "yahoo":
      window.open('http://bookmarks.yahoo.com/toolbar/savebm?u='+url+'&t='+title);    
    break;
    case "oknotizie":
      window.open('http://oknotizie.virgilio.it/post.html.php?url='+url+'&title='+title);
    break;
    case "wikio":
      window.open('http://www.wikio.it/sharethis?url='+url+'&title='+title);
    break;
    case "linkedin":
      window.open('http://www.linkedin.com/shareArticle?mini=true&url='+url+'&title='+title+'&summary=');
    break;
  }  
}

