//---------------------------------------------------------
// Search Functions 
//---------------------------------------------------------

// indexOf function's definition because Internet Explorer does not support it with arrays
if( !Array.indexOf ) {
   Array.prototype.indexOf = function(el) {
      var l = this.length;
      var i = 0;
      while( i < l && this[i] != el ) {
         ++i;
      }
      return i == l ? -1 : i;
   }
}

//---------------------------------------------------------
// browser detection
//---------------------------------------------------------

// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
function getInternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/*
 * -------------------------------------------------------------
 * purpose:    It shows the feedback box
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function showFeedbackBox( lg, ref, imgName ) {
   var html;
   // IFRAME
   // var doc = top.document;
   var doc = document;
   var divFeedback = doc.getElementById("idg1");
   if(divFeedback) {
      var refBit = "";
      if(ref) {
         refBit = "rs_";
      }
         
      if( imgName ) {
         html = '<img src="/img/search2/'+imgName+'_' + refBit + lg + '.gif">';
      }
      else {
         if(ref) {
            html = '<img src="/img/search2/update_' + refBit + lg + '.gif">';
         } else {
            html = '<img src="/img/search2/update_venere_' + refBit + lg + '.gif">';
         }
      }
      divFeedback.innerHTML = html;
      divFeedback.style.visibility ="visible";
      var dimArray = size();
      var height = dimArray[1]/2 - 33;
      var positionArray = getDeltas();
      divFeedback.style.top  = positionArray[1]+height+"px";
   }
}

/*
 * -------------------------------------------------------------
 * purpose:    It unshows the feedback box
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function unshowFeedbackBox() {
   // IFRAME
   // var doc = top.document;
   var doc = document;
   var divFeedback = doc.getElementById("idg1");
   if(divFeedback) {
      divFeedback.innerHTML = "";
      divFeedback.style.visibility ="hidden";
   }
}

/*
 * -------------------------------------------------------------
 * purpose:    It checks if an object is empty
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function isEmptyObject( o ) {
   for( var i in o ) return false;
   return true;
}

/*
 * -------------------------------------------------------------
 * purpose:    It checks if the rating is visible
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function isVisibleRating( type ) {
   return !!Constants.visibleRating[type];
}

/*
 * -------------------------------------------------------------
 * purpose:    Return the path of a property image
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getHotelImagePath(hoteltId, lengthPath) {
   if (hoteltId == 0) {
     return null;
   }
   
   if (lengthPath < 0) {
     return null;
   }
   
   var hotelIdString = "" + hoteltId;
   
   var leadingZero = "";
   var max  = lengthPath;
   var diff = lengthPath - hotelIdString.length;
   
   if (diff > 0) {
      for(var i=0; i < diff ; i++){
        leadingZero += "0/";
      }
      max = max - diff;
   }
   
   var reverseHotelIdString = "";

   for( var index=0; index<hotelIdString.length; index++) {
     reverseHotelIdString += hotelIdString.charAt( hotelIdString.length-index-1 );
   }
   
   //init resultHotelImagePath
   var resultHotelImagePath = "img/hotel/";
   
   for(var i=0; i < max ; i++) {
     resultHotelImagePath += reverseHotelIdString.charAt(i) + "/";
   }
   
   resultHotelImagePath += leadingZero + hotelIdString+"/";

   return resultHotelImagePath;
}

/*
 * -------------------------------------------------------------
 * purpose:    Return the currency symbol
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getCurrencySymbol( currencyCode) {
   if( currencyCode == "EUR" ) {
      return "&euro;";
   }
   else if( currencyCode == "USD" ) {
      return "&#36;";
   }
   else if( currencyCode == "GBP" ) {
      return "&pound;";
   }
   return currencyCode;
}

/*
 * -------------------------------------------------------------
 * purpose:    Return the url queryString
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getQueryString( key, ignoreCase ) {
    var queryString = window.location.search;
    return getQueryStringEx( queryString, key, ignoreCase );    
}

/*
 * -------------------------------------------------------------
 * purpose:    Return the url queryString
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getQueryStringEx( queryString, key, ignoreCase ) {
    if ( ( key == null ) || ( key == "" ) || ( key == undefined ) || ( queryString.length < 2 ) ) { 
      return null;
    }

    if( ignoreCase == true ) {
       key = key.toLowerCase();
       queryString = queryString.toLowerCase();
    }

    var startPos = -1;
    var key_length;
    startPos = queryString.indexOf ( "&" + key + "=");
    key_length = key.length + 2;
    if( startPos == -1 ) {
       startPos = queryString.indexOf ( "?" + key + "=" );
       key_length = key.length + 2;
    } 
    if( startPos == -1 ) {
       startPos = queryString.indexOf ( key + "=" );
       key_length = key.length + 1;
    } 
    
        
    if (startPos == -1) {
       return null;
    }

    startPos += key_length;

    var endPos = queryString.indexOf ("&", startPos);
    if (endPos == -1) {
       endPos = queryString.length;
    }

    return unescape ( queryString.substring ( startPos, endPos ) );
}

/*
 * -------------------------------------------------------------
 * purpose:    Return the url hash
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getQueryStringHash( queryString ) {
    if ( ( queryString == null ) || ( queryString == "" ) || ( queryString == undefined ) || ( queryString.length < 2 ) ) { 
      return null;
    }

    var keyValueArray = queryString.split("&");
    
    var resultArray = new Array();
    for(var i=0; i<keyValueArray.length; i++) {
       var keyValue = keyValueArray[i].split("=");
       if(keyValue && keyValue[0] && keyValue[1]) {
          resultArray[keyValue[0]] = keyValue[1];
       }
    }

    return resultArray;
}

/*
 * -------------------------------------------------------------
 * purpose:    It creates a queryString
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function createQueryString( data ) {
   var queryString = "";
   var flag = false;
   for( key in data ) {
      if( typeof(data[key]) == "function" ) {
         continue;
      }
      if( key && data[key] ) {
         if ( flag ) {
            queryString += "&";
         }
         else {
            flag = true;
         }
         queryString += key + "=" + encodeURIComponent ( data[key] );
      }
   }
   
   return queryString;
}

/*
 * -------------------------------------------------------------
 * purpose:    It adds a param to url
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function addParamToUrl( url, key, value ) {
   if( ( !key) || ( !value ) || ( !url ) ){
      return url;
   }

//   var pos = url.indexOf ("ref=");
//   if( pos != -1) {
//      return url;
//   }
   
   var newUrl = url;   
   pos = newUrl.indexOf ("?");
   
   if (pos == -1) {
      newUrl += "?";
   }
   else if( pos != (newUrl.length - 1) ){
      newUrl += "&";
   }
   
   newUrl += key + "=" + encodeURIComponent( value );
   
   return newUrl;
}

/*
 * -------------------------------------------------------------
 * purpose:    It adds a param string to url
 * @Author:    perone
 * -------------------------------------------------------------
 */
function addParamStringToUrl( url, paramString){

   if(!paramString) return url;
   
   var newUrl = url;   
   var pos = newUrl.indexOf ("?");
   
   if (pos == -1) {
      newUrl += "?";
   }
   else if( pos != (newUrl.length - 1) ){
      newUrl += "&";
   }
  
   newUrl += paramString.replace(/^(\?|&)/,"");
   
   
   
   return newUrl;
}

/*
 * -------------------------------------------------------------
 * purpose:    It replaces a param into the url. 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function replaceParamToUrl( url, key, value ) {
   var oldValue = getQueryString( key, true);
   if( oldValue ){
      url = url.replace(key + "=" + oldValue, key + "=" + value);
   }
   else{
      url = addParamToUrl( url, key, value );
   }
   
   return url;
}

/*
 * -------------------------------------------------------------
 * purpose:    It removes a param from the url 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function removeParamToUrl( url, key ) {
   var value = getQueryString( key, true);
   if( value ){
      url = url.replace(key + "=" + value, "");
      //todo: da fare tutti i casi
      url = url.replace("&&", "&");
   }
   
   return url;
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns the language from the queryString 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getLanguage( ) {
   var lg = getQueryString( "lg", true );  
   var langs = multiLanguage.languages;
   for(var i in langs) {
      if(langs[i] == lg) {
         return lg;
      }
   }

   return ( "en" );
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns the ref from the queryString 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getRef() {
   var ref = getQueryString("ref", true );
   if( ref == null || ref == "" || ref == "0" )
      return null;
   return ref;
}


/*
 * -------------------------------------------------------------
 * purpose:    It returns the pname from the queryString 
 * @Author:    perone
 * -------------------------------------------------------------
 */
function getPName() {
   var pname = getQueryString("pname", true );
   if( pname == null || pname == "" || pname == "0" )
      return null;
   return pname;
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns the taop from the queryString 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getTaOp() {
   return getQueryString("ta_op", true );
}

/*
 * -------------------------------------------------------------
 * Purpose:    It return stay data parameters with a url query-string.
 * @Author:    salatino
 * -------------------------------------------------------------
 */        
function getStayDataUrlParameters()
{   
   var urlParameters = "";
   if(  ctrl.stayData && isValidStayData(  ctrl.stayData )) {
            
      var o = {
         sd: ctrl.stayData.sd,
         sm: ctrl.stayData.sm,
         sy: ctrl.stayData.sy,
         
         ed: ctrl.stayData.ed,
         em: ctrl.stayData.em,
         ey: ctrl.stayData.ey,
         
         rval: ctrl.stayData.rval,
         pval: ctrl.stayData.pval
      };
      
      urlParameters +=  createQueryString( o );
   }  
   
   if(  ctrl.ref &&  ctrl.ref != 0 ) {
      var ref =  ctrl.ref;
      if( urlParameters.length > 0 ) urlParameters += "&";
      urlParameters += "ref=" + ref;
   }
   
   if(  ctrl.taOp &&  ctrl.taOp != 0 ) {
      var taOp =  ctrl.taOp;
      if( urlParameters.length > 0 ) urlParameters += "&";
      urlParameters += "ta_op=" + taOp;
   }

   return urlParameters;
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns the mode from the queryString 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getMode() {
   return getQueryString("mode", true );
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns the selected properties from the queryString 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getCompareSelected() {
   return getQueryString("compare", true );
}

/*
 * -------------------------------------------------------------
 * purpose:    It adds a page state on the language link. 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function addPageStateOnLanguageLink( pageState ) {
   var langs = multiLanguage.languages;
   
   for(var i in langs) {
      var id = "lg_languages_bar_" + langs[i];
      var lg = langs[i];
      
      // IFRAME
      // var doc = top.document;
      var doc = document;
      
      var element  = doc.getElementById(id);

      if( element ) {
         var href = element.href;
         var j = href.indexOf( "#" );
         if( j != -1 ) {
            href = href.substring( 0, j );
         }
         element.href= href + "#" + pageState;
      }
   }
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns true if the user presses the enter button on the keyboard. 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function isEnterKey( userEvent ) {
   var ie = ( navigator.appName.indexOf('Microsoft Internet Explorer') > -1 );      

   var key = "";
   if(ie) {
      try {
         key = top.event.keyCode;
      } catch(e){
         ;//todo:trovare una soluzione nel caso di frame per il ref
      }
      //alert("ie: "+key);
   } 
   else {
      if( userEvent == undefined ) {
         //alert("userEvent = undefined");
         return false;
      }

      key = userEvent.which;
      //alert("no ie: "+key);
   }
   
   return ( key == 13 );
}

/*
 * -------------------------------------------------------------
 * purpose:    It returns the discount price 
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function getDiscountPrice(price, percentage, round) {
   if( !price || !percentage) {
      return null;
   }
   
   if( !round ) {
      round = 2;
   }

   var roundNum = 1;
   for( var i=0; i<round; i++ ) {
      roundNum *= 10;
   }
   
   var newPrice = price - ( price / 100 * percentage );

   newPrice = parseInt( newPrice * roundNum, 10 ) / roundNum;
   
   return newPrice;
}

/*
 * -------------------------------------------------------------
 * purpose:    If Constants.maxRoundDecimal = 1, returns the value of a number rounded to the nearest integer.
 * @Author:    group 5
 * -------------------------------------------------------------
 */
function roundDecimal(value){
   roundDecimals = Constants.roundDecimals;
   if(roundDecimals == 1) {
      return Math.round(value);
   }
   else {
      return value;
   }
}

function displayErrors(msg,url,line) {
   var popupError = window.open('','Debug','scrollbars=yes');
   popupError.document.open();
   
   popupError.document.writeln('<B>Error Report</B>');
   popupError.document.writeln('<B>Error in file:</B> ' + url + '<BR> ');
   popupError.document.writeln('<B>Line number:</B> ' + line + '<BR>');
   popupError.document.writeln('<B>Message:</B> ' + msg);
   
   popupError.document.close();
   
   return true;
}

function trim(StrToTrim){   
   return StrToTrim.replace(/^\s*|\s*$/g,"");   
}

function check_email_address(e) {
   ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

   for (i=0; i < e.length; i++) {
      if (ok.indexOf(e.charAt(i)) < 0) { 
         return (false);
      }   
   } 

   re     = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
   re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
   if (!e.match(re) && e.match(re_two)) {
      return (true);      
   } else {
      return false;
   }
}

function trim(StrToTrim){   
   return StrToTrim.replace(/^\s*|\s*$/g,"");   
}


function check_email_address(e) {
   ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

   for (i=0; i < e.length; i++) {
      if (ok.indexOf(e.charAt(i)) < 0) { 
         return (false);
      }   
   } 

   re     = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
   re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
   if (!e.match(re) && e.match(re_two)) {
      return (true);      
   } else {
      return false;
   }
}


//extended prototypes position to return
//the scrolled window deltas
function getDeltas() {
   var deltaX =  window.pageXOffset || 
                 document.documentElement.scrollLeft || 
                 document.body.scrollLeft || 
                 0;
                 
   var deltaY =  window.pageYOffset || 
                 document.documentElement.scrollTop || 
                 document.body.scrollTop || 
                 0;
                 
   return [deltaX, deltaY];
}

//return working window's size,
//copied this code from the
function size() {
   var winWidth, winHeight, d=document;
   if (typeof window.innerWidth!='undefined') {
      winWidth = window.innerWidth;
      winHeight = window.innerHeight;
   } else {
      if (d.documentElement && 
          typeof d.documentElement.clientWidth!='undefined' && 
          d.documentElement.clientWidth != 0) {
             winWidth = d.documentElement.clientWidth
             winHeight = d.documentElement.clientHeight
      } else {
         if (d.body && typeof d.body.clientWidth!='undefined') {
            winWidth = d.body.clientWidth
            winHeight = d.body.clientHeight
         }
      }
   }
   return [winWidth, winHeight];
}

//------------------------------------------------------------------------------
// debug functions

DEBUG=false;
debug_popup = null;

DEBUG_TIME=false;
debugTimeArray = null;
debugTimeCounter = 0;

function active_debug() {
   DEBUG = true;
   debug_popup = window.open( "", "", "dependent=yes, width=600, heigth=200, scrollbars=yes, resizable=yes" );
}

function active_debug_time() {
   DEBUG_TIME = true;
   debug_popup = window.open( "", "", "dependent=yes, width=600, heigth=200, scrollbars=yes, resizable=yes" );
   debugTimeArray = new Array();
   debugTimeCounter = 0;
}

function disable_debug() {
  DEBUG = false;
}

function disable_debug_time() {
  DEBUG_TIME = false;
}

function debug( msg ) {
   if( DEBUG) {
     debug_popup.document.write( msg + "</br>" );
   }
}

function debugTime( msg, index ) {
   if( DEBUG_TIME) {
      var newDate = new Date();
      var newTime = newDate.getTime();
      
      if( index && index <= debugTimeCounter ) {
         debugTimeArray[index] = new Array(msg, debugTimeArray[index][1] + newTime, debugTimeArray[index][2] + 1);
      }
      else {
         debugTimeArray[debugTimeCounter] = new Array(msg, newTime, 1);
         debugTimeCounter ++;
      }
   }
}

function getIndexLastDebugTime(){
   return debugTimeCounter;
}

function debugDiffTime( msg ) {
   if( DEBUG_TIME) {
      var result = '<table border="1">';
      result += '<tr><td>MESSAGE</td><td>TIME</td><td>DIFF</td></tr>';
      for(var i=0; i<debugTimeArray.length; i++) {
         var diffTime = 0;
         if(i != 0) {
            var firstTime = debugTimeArray[i-1][1];
            var lastTime  = debugTimeArray[i][1];

            if(debugTimeArray[i-1][2] > 1) {
               firstTime = Math.round(firstTime/debugTimeArray[i-1][2]);
            }

            if(debugTimeArray[i][2] > 1) {
               lastTime = Math.round(lastTime/debugTimeArray[i][2]);
            }
            
            diffTime = lastTime - firstTime;
         }
         
         result += '<tr><td>' + debugTimeArray[i][0] + '</td><td>' + debugTimeArray[i][1] + '</td><td>' + diffTime + '</td></tr>';
      }
      
      totalTime = (debugTimeArray[debugTimeArray.length - 1][1] - debugTimeArray[0][1]);
      result += '<tr><td colspan="2">Total time</td><td>' + totalTime + '</td></tr>';
      result += '</table>';
      
      debug_popup.document.write( msg + "</br>" );
      debug_popup.document.write( result + "</br>" );
      
      debugTimeArray = new Array();
      debugTimeCounter = 0;
      debug_popup.document.close();
   }
}



function inspect( obj ) {
  var txt = "";
  for( var x in obj ) {
    txt += x + "\n";
  }
  alert( "inspect \n" + txt );
}

function toStr( obj, l ) {
   
   var txt = "";
   if( !l ) {
      l = 0;
   }
   
   for( var k in obj ) {
      for( var i = 0; i < l ; ++i ) {
         txt += ". ";
      }
      txt += k + " ";
      if( typeof( obj[k] ) == "object" ) {
         txt += toStr( obj[k] );         
      } else {
         txt += obj[k];
      }
      txt += "\n";
   }
   return txt;
}

function inspect2( obj ) {
   alert( toStr( obj ) );
}

function inspectXML( xmlNode, l ) {
  
  var level = (l) ? l : 0;
 
  var txt = "";
  var i = 0;
 
  // indentations
  for( i = 0; i < level; i++ ) {
    txt += " ";
  }
  
  // node info
  txt += xmlNode.nodeName + " type:" + xmlNode.nodeType + " ";
  
  // attributes
  if( xmlNode.hasAttributes() ) {
    var attributes = xmlNode.attributes;
    for( i = 0; i < attributes.length; i++ ) {
      txt += attributes[i].name + "=" + attributes[i].value + " ";
    }
  }
  
  // childs
  txt += "\n";
  var childs = xmlNode.childNodes;
  for( i = 0; i < childs.length; i++ ) {
    txt += inspectXML( childs[i], level + 1 );
  }
  return txt;
}

function inspectResponse() {
  // inspectObject( this.req.responseXML );
  txt = "<pre>" + inspectXMLNode( this.req.responseXML ) + "</pre>";
  //divOutput = document.getElementById("debug");
  //divOutput.innerHTML += txt;
}

// shuffle(vector: Array): Array
// Returns an array with the values scrambled.           
// v: array that will be scrambled and will not be changed
function arrayShuffle(input) {
    var v = input.slice(0); //clone input Array
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
}

//---------------------------------------------------------
// End Search Functions 
//---------------------------------------------------------
