var isIE = document.all ? true : false;
var imgIndex = -1;
var imgArray = new Array();
var hDiv;
var bDiv;
var slTimeout;
var showing = new Array();
var newsID = 0;
var imgUrls = new Array();
var imgCache = [];

function init() {
  var s = pos.substr(1,1);
  var p = pos.length == 8 ? parseInt(pos.substr(6,2)) : 0;
  var sp = pos.substr(3,2);
  resize_window();
  $(window).resize(resize_window);

//  if (item == 1) {
//    $('.prod_label').css('color','#97012d');
//  }

  var oLang = lang == 'en' ? 'it' : 'en';

  if (/(iPhone|iPod|Android.*Mobile|webOS|NetFront|Opera Mini|SEMC-Browser|PlayStation Portable|Nintendo Wii|BlackBerry)/
    .test( navigator.userAgent ) ) {
      $('#linguamob').css('display','block');
    if ($('#langm'+lang).length) {
      var h = $('#langm'+lang).children().html();
      $('#langm'+lang).html(h);
    }
    $('#langm'+oLang).css('cursor','pointer').bind('click',function () { changeLang(oLang); });
  }
  else {
    if ($('#lang'+lang).length) {
      var h = $('#lang'+lang).children().html();
      $('#lang'+lang).html(h);
    }
    $('#lang'+oLang).css('cursor','pointer').bind('click',function () { changeLang(oLang); });
    $('#lingua').css('display','block');
  }

  if ($('#testo').length == 0 && pos != '02.00') {
    if ($('#level2 a.sel').length) {
      var oo = $('#level2 a.sel').next().children().children();
      if ($(oo).length) {
	if ($(oo).get(0).nodeName == 'A') {
	  window.location.href = $(oo).attr('href');
	  return;
	}
      }
    }
    else {
       if (sp == '00' && $('#level1 a.sel').length) {
	var oo = $('#level2 a:first');
	if ($(oo).length && $(oo).get(0).nodeName == 'A') {
	  window.location.href = $(oo).attr('href');
	  return;
	}
     }
    }
  }
  else {
    $('#showText').bind('click',function () { textShowHide(); });
    $('#showText2').bind('click',function () { textShowHide(); });
  }

  if (typeof(imgNames) != "undefined") {
    preloading();
  }
  else {
    if ($('#bg_image').length)   $('#bg_image').css('display','block');
  }

  if ($('#myform').length) {
    $('#testo').show();
    init_form();
    return;
  }

  if ($('#testo').length) {
    if (pos.match(/^02\.0[1-3]/))
      $('#testo').show();
    else if (pos == '06.03')
      $('#testo').show(); // form newsletter
    $('#myaddthis').show();

    return;
  }

  if ($('#testonews').length) {
    $('#myaddthis').css({top:'40px',left:'670px'}).show();
    return;
  }

  if ($('#press').length) {
    $('#myaddthis').css({top:'130px',left:'797px'}).show();
    return;
  }
  if ($('#awards').length) {
    $('#myaddthis').css({top:'130px',left:'797px'}).show();
    return;
  }


}

var textOn = 1;
function textShowHide() {
  if (textOn == 0) {
    $('#testo').hide();
    $('#testo2').fadeIn(1000);
    textOn = 1;
  }
  else {
    textOn = 0;
    $('#testo2').fadeOut(1000, function () { $('#testo').show(); });
  }
}

var loaded = 0;
function preloading () {
  if (imgNames) {
    if (imgNames.length < 2) return;
  }

//  $('<img>').attr('id','bg_image2').appendTo($('body'));

//  setTimeout(sliding,5000);
  for (var i=0;i<imgNames.length;i++) {
    imgUrls[i] = imagePath + imgNames[i];
//    alert(imgUrls[i]);
  }

  jQuery.preLoadImages(imgUrls);

  return;
  if ( imgUrls ) {
    if (imgUrls.length < 2) return;
  }

  jQuery.preLoadImages(imgUrls);
  //loadImgs();
}

var errorTimer;
function loadImgs() {
  //only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...)
  // otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads
  if(imgUrls && imgUrls.length) {
    if (imgUrls[loaded]){
      imgArray[loaded] = new Image(); //new img obj
      imgArray[loaded].src = imgUrls[loaded];//set src either absolute or rel to css dir
      if(!imgArray[loaded].complete){
	jQuery(imgArray[loaded]).bind('error load onreadystatechange', onImgComplete);
      } else {
	onImgComplete();
      }
      //errorTimer = setTimeout(onImgComplete, 999); // handles 404-Errors in IE
    }
    else {
//      for (var i=0;i<imgUrls.length;i++) alert(imgArray[i].src);
      $('#slider :first-child').addClass('selected');
      slTimeout = setTimeout('sliding()',2500);
    }
  }
}

function onImgComplete () {
  clearTimeout(errorTimer);
  var ind = parseInt(loaded+1);
//OLD_SLIDER  $('#slider ul li:nth-child('+ind+')').css('visibility','visible');
  $('#slider :nth-child('+ind+')').css('visibility','visible');
  if (imgUrls && imgUrls.length && imgUrls[loaded]) {
    loaded++;
    loadImgs();
  }
//  else {
//    $('#slider :first-child').addClass('selected');
//    slTimeout = setTimeout('sliding()',2500);
//  }
}


function firstShow() {
  imgIndex = 0;
  $('#bg_image').attr('src',imgCache[0].src);
  $('#bg_image').fadeIn( 500, function () {
		       setTimeout(sliding,5000);
			    });

}

function sliding() {
  imgIndex++;
  if (imgIndex == imgCache.length) {
  //  return;
    imgIndex = 0;
  }
  var n,o;
  if (imgIndex % 2) {
    n = 2;
    o = '';
  }
  else {
    n = '';
    o = 2;
  }

  $('#bg_image'+o).fadeOut(500);
  $('#bg_image'+n).attr('src',imgCache[imgIndex].src);
  $('#bg_image'+n).fadeIn( 500, function () {
		       setTimeout(sliding,5000);
			    });
}


function set_png_background(obj, img, path) {
	path = path || '';
	img = path + img;
	if (isIE)
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img + "',sizingMethod='scale')";
	else
		obj.style.backgroundImage = 'url(' + img + ')';
}

function get_elements_by_class_name(node, str) {
	var elems = new Array();
	var all_tags = node.getElementsByTagName('*');
	var l = all_tags.length;
	for (var i = 0; i < l; i++) {
		var cur_tag = all_tags[i];
		if (cur_tag.className.indexOf(str) != -1) elems.push(cur_tag);
	}
	return elems;
}

function changeLang(l) {
  if (l == lang) return;
  lang = l;
  if (item != 0)
    gotoPage(pos,item);
  else
    gotoPage(pos);
}


function gotoPage(pos,item) {
  var i,n;
  var u = new String(window.document.location);
  if (u.indexOf('news'))
    n = newsID  != 0 ? '&news='+newsID : '';
  i = '';
  if (typeof(item) != "undefined")
//  if (u.indexOf('item'))
    i = item != 0 ? '&item='+item : '';


  window.document.location.href = 'index.pl?pos='+pos+'&lang='+lang+i+n;
}

(function($) {
   // Arguments are image paths relative to the current page.
   imgCache = [];
   $.preLoadImages = function(arr) {
     for (var i=0;i<arr.length;i++) {
      // alert(arr[i]);
       var cacheImage = document.createElement('img');
       cacheImage.src = arr[i];
//       $(cacheImage).load(function () {
//			    loadDone(this,i);
//			  });
       imgCache.push(cacheImage);
     }
     startSliding();
   }
 })(jQuery);

function startSliding() {
  if (imgCache[0].complete)
    firstShow();
  else
    setTimeout(startSliding,50);
}

function loadDone (o,i) {
//  alert('done:'+$(o).attr('src'));
//  alert(i + ' ' + imgCache.length);
  alert(o.complete);
}



function resize_window (){
    var current_h =$(window).height();
    var current_w =$(window).width();
    var ratio=current_w/current_h;

    if (ratio<1.3) {
      $('#bg_image').css('height','100%').css('width','auto').css('display','block');
      $('#bg_image2').css('height','100%').css('width','auto');
    }
    else {
      $('#bg_image').css('width','100%').css('height','auto').css('display','block');
      $('#bg_image2').css('widtht','100%').css('height','auto');
    }

}
