﻿var addthis_config = { data_ga_tracker: "pageTracker", ui_click: true, ui_language: "it", data_track_clickback: true, data_track_linkback: true };
var addthis_localize = { share_caption: "InSardegna.tv" };
var NewWinMessage = " (apre collegamento in una nuova finestra)";
var ShowTabs = false;
var SlideShow = false;

$(document).ready(
   function() {
      SetTargetBlankJQ(); //inizializza class=targetBlank
      popupExternal(); //inizializza rel=external
      if (ShowTabs == true) { $("#tabsVideo").tabs(); };
      if (SlideShow == true) { slideShow(5000) }
   } //function
);    //document.ready

function slideShow(speed) {
   //append a LI item to the UL list for displaying caption
   $('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>');
   //Set the opacity of all images to 0
   $('ul.slideshow li').css({ opacity: 0.0 });
   //Get the first image and display it (set it to full opacity)
   $('ul.slideshow li:first').css({ opacity: 1.0 });
   //Get the caption of the first image from REL attribute and display it
   $('#slideshow-caption h3').html($('ul.slideshow a:first').find('img').attr('title'));
   $('#slideshow-caption p').html($('ul.slideshow a:first').find('img').attr('alt'));
   //Display the caption
   $('#slideshow-caption').css({ opacity: 0.7, bottom: 0 });
   //Call the gallery function to run the slideshow
   var timer = setInterval('slideShowGallery()', speed);
   //pause the slideshow on mouse over
   $('ul.slideshow').hover(function() { clearInterval(timer); }, function() { timer = setInterval('slideShowGallery()', speed); });
}

function slideShowGallery() {
   //if no IMGs have the show class, grab the first image
   var current = ($('ul.slideshow li.show') ? $('ul.slideshow li.show') : $('#ul.slideshow li:first'));
   //Get next image, if it reached the end of the slideshow, rotate it back to the first image
   var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption') ? $('ul.slideshow li:first') : current.next()) : $('ul.slideshow li:first'));
   //Get next image caption
   var title = next.find('img').attr('title');
   var desc = next.find('img').attr('alt');
   //Set the fade in effect for the next image, show class has higher z-index
   next.css({ opacity: 0.0 }).addClass('show').animate({ opacity: 1.0 }, 1000);
   //Hide the caption first, and then set and display the caption
   //$('#slideshow-caption').animate({ bottom: -70 }, 300, function() {
   //Display the content
      $('#slideshow-caption').animate({ bottom: -70 }, 300);
      $('#slideshow-caption h3').html(title);
      $('#slideshow-caption p').html(desc);
      $('#slideshow-caption').animate({ bottom: 0 }, 500);
   //});
   //Hide the current image
   current.animate({ opacity: 0.0 }, 1000).removeClass('show');
}
   
function switchViews(obj) { $('#' + obj).slideToggle(); }

function SetTargetBlankJQ() {
   $("a.targetBlank").each(function(e) {
      var newTitle = $(this).attr("title") + NewWinMessage; $(this).removeAttr("title"); $(this).attr("title", newTitle);
      $(this).click(function() { window.open(this.href); return false; })
   });
};

//utilizzo: <a href='url' rel='external' /> oppure <a href='url' rel='external[640,480]' />
function popupExternal() {
   var popupRE = /external\[(\d+),(\d+)\]/gi; var links = $('a[rel^="external"]'); var rel, width, height;
   links.click(function() {
      rel = $(this).attr('rel');
      if (rel == "external") { window.open($(this).attr('href')); return false; }
      else if (rel.match(popupRE)) {
         width = RegExp.$1; height = RegExp.$2;
         window.open($(this).attr('href'), '', 'width=' + width + ',height=' + height + ',scrollbars=yes'); return false;
      }
   });
   links.each(function(e) {
      rel = $(this).attr('rel');
      if (rel == "external" || rel.match(popupRE)) {
         var newTitle = $(this).attr("title") + NewWinMessage; $(this).removeAttr("title"); $(this).attr("title", newTitle);
      }
   });
}

function newwin(url,nome,larghezza,altezza) {
   finestra = window.open(url,nome,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+larghezza+",height="+altezza);
   return false;
}

function SetTargetBlank() {
	if(document.getElementsByTagName)
	{
		var i;
		var msg = " (apre collegamento in una nuova finestra)";
		var links = document.getElementsByTagName("a");
		for (i = 0; i < links.length; i++)
		{
			var link = links[i];
			if (link.className.indexOf("targetBlank") != -1)
			{
				link.title += msg;
				var fn = function()
				{
					window.open(this.href);
					return false;
				}
				link.onclick = fn;
				link.onkeypress = fn;
			}
		}
	}
}

function addImgPanoramio(imgSrc, imgTitle) {
   document.getElementById('imgPanoramioBig').src = imgSrc;
   document.getElementById('imgPanoramioBig').alt = imgTitle;
   document.getElementById('imgPanoramioBig').title = imgTitle;
   document.getElementById('imgPanoramioText').innerText = imgTitle;
}

function showimage(elemento, immagine) {
   elemento.src = immagine;
}

function getFrameVideoMap(vid) {
   document.write("<iframe src='/servizi/videomap.aspx?vid=" + vid + "' id='GMapVideoContainer' style='width:350px; height:350px; border:none; overflow:hidden;'></iframe>")
}

function centreWinPopUp(pageFile, popUpName, w, h, scroll, resize) {
	var winLeft = (screen.width - w) / 2;
	var winTop = (screen.height - h) / 2;
	winProperties = 'height='+h+',width='+w+',top='+winTop+',left='+winLeft+',scrollbars='+scroll+',toolbar=no,resizable='+resize+',status=no'
	if (!window.winPopUp)
	   {winPopUp = window.open(pageFile, popUpName, winProperties)}
	else
	{
		if (!winPopUp.closed)
		   {winPopUp.focus();}
		else
		   {winPopUp = window.open(pageFile, popUpName, winProperties)}
	}	
}

/**
* jQuery Maxlength plugin
* @version		$Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $
* @package		jQuery maxlength 1.0.5
* @copyright	Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se
* @license		GNU/GPL, see LICENSE.txt
*/
(function($) {
	$.fn.maxlength = function(options) {
		var settings = jQuery.extend(
		{
			events: [], // Array of events to be triggerd
			maxCharacters: 10, // Characters limit
			status: true, // True to show status indicator bewlow the element
			statusClass: "status", // The class on the status div
			statusText: "caratteri rimanenti", // The status text
			notificationClass: "notification", // Will be added to the emement when maxlength is reached
			showAlert: false, // True to show a regular alert message
			alertText: "Hai digitato troppi caratteri.", // Text in the alert message
			slider: false // Use counter slider
		}, options);
		$.merge(settings.events, ['keyup']); // Add the default event
		return this.each(function() {
			var item = $(this);
			var charactersLength = $(this).val().length;
			// Update the status text
			function updateStatus() {
				var charactersLeft = settings.maxCharacters - charactersLength;
				if (charactersLeft < 0) { charactersLeft = 0; }
				item.next("div").html(charactersLeft + " " + settings.statusText);
			}
			function checkChars() {
				var valid = true;
				// Too many chars?
				if (charactersLength >= settings.maxCharacters) {
					valid = false; // Too may chars, set the valid boolean to false
					item.addClass(settings.notificationClass); // Add the notifycation class when we have too many chars
					item.val(item.val().substr(0, settings.maxCharacters)); // Cut down the string
					showAlert(); // Show the alert dialog box, if its set to true
				}
				else {
					if (item.hasClass(settings.notificationClass)) { item.removeClass(settings.notificationClass); }  // Remove the notification class
				}
				if (settings.status) { updateStatus(); }
			}
			// Shows an alert msg
			function showAlert() {
				if (settings.showAlert) { alert(settings.alertText); }
			}
			// Check if the element is valid.
			function validateElement() {
				var ret = false;
				if (item.is('textarea')) { ret = true; } else if (item.filter("input[type=text]")) { ret = true; } else if (item.filter("input[type=password]")) { ret = true; }
				return ret;
			}
			// Validate
			if (!validateElement()) { return false; }
			// Loop through the events and bind them to the element
			$.each(settings.events, function(i, n) {
				item.bind(n, function(e) { charactersLength = item.val().length; checkChars(); });
			});
			// Insert the status div
			if (settings.status) { item.after($("<div/>").addClass(settings.statusClass).html('-')); updateStatus(); }
			// Remove the status div
			if (!settings.status) {
				var removeThisDiv = item.next("div." + settings.statusClass);
				if (removeThisDiv) { removeThisDiv.remove(); }
			}
			// Slide counter
			if (settings.slider) {
				item.next().hide();
				item.focus(function() { item.next().slideDown('fast'); });
				item.blur(function() { item.next().slideUp('fast'); });
			}
		});
	};
})(jQuery);

var FontSizeMin=10;
var FontSizeMax=18;

function AumentaFontArticolo() {
   increaseFontSize('div#testoArticolo');
   increaseFontSize('div#testoArticolo p');
   increaseFontSize('div#testoArticolo div');
}
function DiminuisciFontArticolo() {
   decreaseFontSize('div#testoArticolo');
   decreaseFontSize('div#testoArticolo p');
   decreaseFontSize('div#testoArticolo div');
}
function increaseFontSize(selector) {
   var list = getElementsBySelector(selector);
   for (j=0; list[j]; j++) {
      if(list[j].style.fontSize) {
         var s = parseInt(list[j].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=FontSizeMax) {
         s += 1;
      }
      list[j].style.fontSize = s+"px"
   }
}
function decreaseFontSize(selector) {
   var list = getElementsBySelector(selector);
   for (j=0; list[j]; j++) {
      if(list[j].style.fontSize) {
         var s = parseInt(list[j].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=FontSizeMin) {
         s -= 1;
      }
      list[j].style.fontSize = s+"px"
   }
}
// riferimento: simon.incutio.com/archive/2003/03/25/getElementsBySelector
function getElementsBySelector(selector) {
// Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}