/*
  $Id: general.js,v 1.3 2003/02/10 22:30:55 hpdl Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/
// funzione avanzata di ricerca oggetto...
function $( oName, oFrame, oDoc ) {
	if( !oDoc ) { if( oFrame ) { oDoc = oFrame.document; } else { oDoc = window.document; } }
	if( oDoc[oName] ) { return oDoc[oName]; } if( oDoc.all && oDoc.all[oName] ) { return oDoc.all[oName]; }
	if( oDoc.getElementById && oDoc.getElementById(oName) ) { return oDoc.getElementById(oName); }
	var x; var theOb;
	for( x = 0; x < oDoc.forms.length; x++ ) { if( oDoc.forms[x][oName] ) { return oDoc.forms[x][oName]; } }
	for( x = 0; x < oDoc.anchors.length; x++ ) { if( oDoc.anchors[x].name == oName ) { return oDoc.anchors[x]; } }
	for( x = 0; document.layers && x < oDoc.layers.length; x++ ) {
		theOb = MWJ_findObj( oName, null, oDoc.layers[x].document ); if( theOb ) { return theOb; } }
	if( !oFrame && window[oName] ) { return window[oName]; } if( oFrame && oFrame[oName] ) { return oFrame[oName]; }
	for( x = 0; oFrame && oFrame.frames && x < oFrame.frames.length; x++ ) {
		theOb = MWJ_findObj( oName, oFrame.frames[x], oFrame.frames[x].document ); if( theOb ) { return theOb; } }
	return null;
}

// ricerca per classname
function $$(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function Array_shift(array) {
  var A_s = 0
  var response = array[0]
  for (A_s = 0; A_s < array.length-1; A_s++) {
   array[A_s] = array[A_s + 1]
   }
  array.length--
  return array
  }

function SetFocus(TargetFormName) {
  var target = 0;
  if (TargetFormName != "") {
    for (i=0; i<document.forms.length; i++) {
      if (document.forms[i].name == TargetFormName) {
        target = i;
        break;
      }
    }
  }

  var TargetForm = document.forms[target];
    
  for (i=0; i<TargetForm.length; i++) {
    if ( (TargetForm.elements[i].type != "image") && (TargetForm.elements[i].type != "hidden") && (TargetForm.elements[i].type != "reset") && (TargetForm.elements[i].type != "submit") ) {
      TargetForm.elements[i].focus();

      if ( (TargetForm.elements[i].type == "text") || (TargetForm.elements[i].type == "password") ) {
        TargetForm.elements[i].select();
      }

      break;
    }
  }
}

function RemoveFormatString(TargetElement, FormatString) {
  if (TargetElement.value == FormatString) {
    TargetElement.value = "";
  }

  TargetElement.select();
}

function CheckDateRange(from, to) {
  if (Date.parse(from.value) <= Date.parse(to.value)) {
    return true;
  } else {
    return false;
  }
}

function IsValidDate(DateToCheck, FormatString) {
  var strDateToCheck;
  var strDateToCheckArray;
  var strFormatArray;
  var strFormatString;
  var strDay;
  var strMonth;
  var strYear;
  var intday;
  var intMonth;
  var intYear;
  var intDateSeparatorIdx = -1;
  var intFormatSeparatorIdx = -1;
  var strSeparatorArray = new Array("-"," ","/",".");
  var strMonthArray = new Array("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");
  var intDaysArray = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

  strDateToCheck = DateToCheck.toLowerCase();
  strFormatString = FormatString.toLowerCase();
  
  if (strDateToCheck.length != strFormatString.length) {
    return false;
  }

  for (i=0; i<strSeparatorArray.length; i++) {
    if (strFormatString.indexOf(strSeparatorArray[i]) != -1) {
      intFormatSeparatorIdx = i;
      break;
    }
  }

  for (i=0; i<strSeparatorArray.length; i++) {
    if (strDateToCheck.indexOf(strSeparatorArray[i]) != -1) {
      intDateSeparatorIdx = i;
      break;
    }
  }

  if (intDateSeparatorIdx != intFormatSeparatorIdx) {
    return false;
  }

  if (intDateSeparatorIdx != -1) {
    strFormatArray = strFormatString.split(strSeparatorArray[intFormatSeparatorIdx]);
    if (strFormatArray.length != 3) {
      return false;
    }

    strDateToCheckArray = strDateToCheck.split(strSeparatorArray[intDateSeparatorIdx]);
    if (strDateToCheckArray.length != 3) {
      return false;
    }

    for (i=0; i<strFormatArray.length; i++) {
      if (strFormatArray[i] == 'mm' || strFormatArray[i] == 'mmm') {
        strMonth = strDateToCheckArray[i];
      }

      if (strFormatArray[i] == 'dd') {
        strDay = strDateToCheckArray[i];
      }

      if (strFormatArray[i] == 'yyyy') {
        strYear = strDateToCheckArray[i];
      }
    }
  } else {
    if (FormatString.length > 7) {
      if (strFormatString.indexOf('mmm') == -1) {
        strMonth = strDateToCheck.substring(strFormatString.indexOf('mm'), 2);
      } else {
        strMonth = strDateToCheck.substring(strFormatString.indexOf('mmm'), 3);
      }

      strDay = strDateToCheck.substring(strFormatString.indexOf('dd'), 2);
      strYear = strDateToCheck.substring(strFormatString.indexOf('yyyy'), 2);
    } else {
      return false;
    }
  }

  if (strYear.length != 4) {
    return false;
  }

  intday = parseInt(strDay, 10);
  if (isNaN(intday)) {
    return false;
  }
  if (intday < 1) {
    return false;
  }

  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth)) {
    for (i=0; i<strMonthArray.length; i++) {
      if (strMonth == strMonthArray[i]) {
        intMonth = i+1;
        break;
      }
    }
    if (isNaN(intMonth)) {
      return false;
    }
  }
  if (intMonth > 12 || intMonth < 1) {
    return false;
  }

  intYear = parseInt(strYear, 10);
  if (isNaN(intYear)) {
    return false;
  }
  if (IsLeapYear(intYear) == true) {
    intDaysArray[1] = 29;
  }

  if (intday > intDaysArray[intMonth - 1]) {
    return false;
  }
  
  return true;
}

function IsLeapYear(intYear) {
  if (intYear % 100 == 0) {
    if (intYear % 400 == 0) {
      return true;
    }
  } else {
    if ((intYear % 4) == 0) {
      return true;
    }
  }

  return false;
}

/**** DYNAMIC ON EVERY PAGE *****/
function pageObj()
{
	var thisObj = this;
	thisObj.newsIndex = 1;
	thisObj.newsTimer = setInterval("page.changeStaticNews()", 3000);
	thisObj.initPage();
	thisObj.initMenu();
	thisObj.initWait();
	thisObj.initImages();
	thisObj.initSlides();
	// ctrls
}
pageObj.prototype.initPage = function()
{
	var thisObj = this;
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	thisObj.searchObj = $('search-main');
	thisObj.searchObj.onkeyup = function() { thisObj.waitFilteringCount(); }
	thisObj.searchResultsObj = $('search-results');
	var userAgent = navigator.userAgent.toLowerCase(),lf=thisObj.searchObj.offsetLeft;
	if(/msie/.test( userAgent ) && !/opera/.test( userAgent )) lf+=$('page-container').offsetLeft;
	thisObj.searchResultsObj.style.left = lf+'px';
}

pageObj.prototype.initWait = function()
{
	var thisObj = this;
	
	thisObj.waitDiv = document.createElement('DIV');
	thisObj.waitDiv.setAttribute('id', 'loading');
	thisObj.waitDiv.style.position = 'absolute';
	thisObj.waitDiv.style.display = 'none';
	thisObj.waitDiv.style.top = '0';
	thisObj.waitDiv.style.left = '0';
	thisObj.waitDiv.style.zIndex = '1000';
	document.body.appendChild(thisObj.waitDiv);
	thisObj.loadImage = document.createElement('img');
	thisObj.loadImageClose = document.createElement('img');
	thisObj.waitImage = document.createElement('img');
	thisObj.waitImage.style.position = 'absolute';
	var loadPreloader = new Image();
	loadPreloader.onload=function()
	{
		loadPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs
		thisObj.loadImage.src = loadPreloader.src;
		thisObj.waitImage.src = loadPreloader.src;
		thisObj.loadImage.width = loadPreloader.width;
		thisObj.loadImage.height = loadPreloader.height;
		return false;
	}
	loadPreloader.src = 'templates/default/images/loading.gif';
	thisObj.loadImageClose.src = 'templates/default/images/close.gif';
	thisObj.loadImageClose.style.position = 'absolute';
	thisObj.loadImageClose.alt = 'Chiudi';
	thisObj.loadImageClose.title = 'Chiudi';
	//thisObj.waitImage.src = 'templates/default/images/loading.gif';
	thisObj.waitDiv.appendChild(thisObj.waitImage);
	thisObj.waitDiv.appendChild(thisObj.loadImageClose);
}
pageObj.prototype.initImages = function()
{
	var thisObj = this;
	var popImages = $$(document, 'A', '*');
	for (var i=0; i<popImages.length; i++)
	{
		if (popImages[i].getAttribute('rel') == 'popImage')
		{
			popImages[i].onclick = function() { return thisObj.openImage(this.href); }
		}
	}
}
pageObj.prototype.openImage = function(href)
{
	var thisObj = this;
	thisObj.wait(1);
	var imgPreloader = new Image();
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function()
	{
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		//window.open(imgPreloader.src, null, 'width='+imgPreloader.width+',height='+imgPreloader.height+',resizable=no,scrollbars=no,status=no');
		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs
		thisObj.waitImage.style.visibility = 'hidden';
		thisObj.waitImage.src = imgPreloader.src;
		thisObj.waitImage.width = imgPreloader.width;
		thisObj.waitImage.height = imgPreloader.height;
		thisObj.waitImage.style.cursor = 'pointer';
		var tempTop = arrayPageScroll[1] + ((arrayPageSize[3] - thisObj.waitImage.height) / 2);
		if (tempTop < 0)
			tempTop = 0;
		thisObj.waitImage.style.top = (tempTop + 'px');
		thisObj.waitImage.style.left = (((arrayPageSize[0] - thisObj.waitImage.width) / 2) + 'px');
		thisObj.waitImage.onclick = function() { thisObj.closeImage() }
		thisObj.loadImageClose.style.cursor = 'pointer';
		thisObj.loadImageClose.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - thisObj.waitImage.height) / 2) + 'px');
		thisObj.loadImageClose.style.left = (((arrayPageSize[0] - thisObj.waitImage.width) / 2) + thisObj.waitImage.width - 14 + 'px')
		thisObj.loadImageClose.onclick = function() { thisObj.closeImage() }
		thisObj.waitImage.style.visibility = 'visible';
		return false;
	}
	imgPreloader.src = href;
	
	return false;
}
pageObj.prototype.closeImage = function( )
{
	var thisObj = this;
	thisObj.waitImage.src = 'templates/default/images/loading.gif';
	thisObj.waitImage.style.cursor = 'default';
	thisObj.waitImage.onclick = function() { };
	thisObj.wait(0);
}
pageObj.prototype.wait = function( toOpen )
{
	var thisObj = this;
	
	if (toOpen == 1)
	{
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		thisObj.waitDiv.style.width = '100%';
		thisObj.waitDiv.style.height = (arrayPageSize[1]+'px');
		thisObj.waitImage.src = thisObj.loadImage.src;
		thisObj.waitImage.width = thisObj.loadImage.width;
		thisObj.waitImage.height = thisObj.loadImage.height;
		thisObj.waitImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - thisObj.waitImage.height) / 2) + 'px');
		thisObj.waitImage.style.left = (((arrayPageSize[0] - thisObj.waitImage.width) / 2) + 'px');
		thisObj.waitDiv.style.display = 'block';
	}
	else
	{
		thisObj.waitDiv.style.display = 'none';
	}
	
}
pageObj.prototype.changeNews = function()
{
	var thisObj = this;
	
	var Ajax = new AjaxObj();
	Ajax.makeRequest( 'post', 'index.php?load=newsflash&after='+thisObj.newsIndex+'&onthefly=true', thisObj.displayNews );
}
pageObj.prototype.changeStaticNews = function()
{
	var thisObj = this;
	
	var lis = $('static-news')? $('static-news').getElementsByTagName('LI') : new Array();
	for (var i=0; i<lis.length; i++)
	{
		if (thisObj.newsIndex == i)
			lis[i].style.display = 'block';
		else
			lis[i].style.display = 'none';
	}
	if (thisObj.newsIndex >= lis.length-1)
		thisObj.newsIndex = 0;
	else
		thisObj.newsIndex++;
}
pageObj.prototype.displayNews = function( response )
{
	$('header-news-content').innerHTML = response;
	page.newsIndex = page.newsIndex + 1;
}
pageObj.prototype.initMenu = function( )
{
	var macros = $$($("top-menu"), 'LI', 'macro');
	for (var i=0; i<macros.length; i++)
	{
		macros[i].onmouseover = function() { page.openMenu( this ); }
		macros[i].onmouseout = function() { page.closeMenu( this ); }
	}
}

pageObj.prototype.openMenu = function( ul )
{
	ul.className = 'macro menu-over';
}
pageObj.prototype.closeMenu = function( ul )
{
	ul.className = 'macro menu-out';
}

/*** SEARCH - RESULT ****/
pageObj.prototype.waitFilteringCount = function( )
{
	var thisObj = this;
	if (thisObj.searchObj.value.length > 2)
	{
		if (thisObj.searchResultsWait)
			clearTimeout(thisObj.searchResultsWait);
		thisObj.searchResultsWait = setTimeout("page.filteringCount()", 700);
	}
}
pageObj.prototype.filteringCount = function( )
{
	var thisObj = this;
	
	if (thisObj.searchResultsHide)
		clearTimeout(thisObj.searchResultsHide);

	var getString = 'index.php?load=search-results&task=module';
	getString += '&search='+thisObj.searchObj.value;
	getString += '&onthefly=true';
	//
	var Ajax = new AjaxObj();
	Ajax.makeRequest( 'post', getString, thisObj.showResultsCount );
	
	return false;
}

pageObj.prototype.showResultsCount = function( response )
{
	$('search-results').innerHTML = response;
	$('search-results').style.visibility = 'visible';
	page.searchResultsHide = setTimeout("$('search-results').style.visibility = 'hidden'", 3000);
}


/*** BROWSER RELATED ****/

pageObj.prototype.errorMsg = function()
{
  alert("Funzione non disponibile per il browser da lei in uso.");
}

pageObj.prototype.addEngine = function(base, name,cat)
{
  if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function"))
  {
    window.sidebar.addSearchEngine(
      base + "includes/firefox/mieilibri.src",
      base + "includes/firefox/mieilibri.gif",
      name,
      cat );
  }
  else
  {
    errorMsg();
  }
}

pageObj.prototype.addBookmark = function(a, url, title)
{
	if (window.sidebar)
    {
    	alert("Puoi aggiungere ai segnalibri di Firefox la pagina che stai visitando premendo CTRL+D");

    } else if( window.opera && window.print )
    {
		alert("Puoi aggiungere ai segnalibri di Opera la pagina che stai visitando premendo CTRL+D (oppure CTRL+T nelle versioni meno recenti)");
    } else if( document.all )
    {
		window.external.AddFavorite( url, title);
    } 
	else alert("Puoi aggiungere ai segnalibri la pagina che stai visitando premendo CTRL+D");
}

window.onload = function() { page = new pageObj(); }


/******************* A J A X ************/

function AjaxObj()
{
	var thisAjaxObj = this;
	thisAjaxObj.request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");
}

AjaxObj.prototype.makeRequest = function(_method, _url, _callback)
{
	var thisAjaxObj = this;
    
	thisAjaxObj.request.onreadystatechange = function() { thisAjaxObj.onResponse(_callback); }
    thisAjaxObj.request.open(_method, _url, true);
  	thisAjaxObj.request.send(_url);
}

AjaxObj.prototype.onResponse = function(_callback)
{
	var thisAjaxObj = this;
	if( thisAjaxObj.request.readyState == 4 )
    {
    	_callback( thisAjaxObj.request.responseText );
   	}
}


