// --- [start /site/generic.js] ---
// JavaScript Document
/* 
* Author : UI Development Team
* Description : lastminute.com Javascript - site wide functionality
* Contact : uidevelopment@lastminute.com
* Resource : http://www.prettyprinter.de - Used for formatting. 
*/

/* Description: Variables to detect environment */

var frontierProtocol = 'http';
var frontierHTTPHost = 'www.lastminute.com';
var frontierBaseUrl = '/site';
var frontierURL = frontierProtocol+'://'+frontierHTTPHost+''+frontierBaseUrl;
var frontierSkin = 'engb.bmibaby';
var frontierLocale = 'en_GB';

/*
* Description : Adds to DOM the jsEnabled class name to indicate javascript availability 
*/
if (document.documentElement && document.getElementById) {
    document.documentElement.setAttribute('class','jsEnabled');
    document.documentElement.className = 'jsEnabled'; //For IE
}
var addJSnotifier = function () {
  var ids = 0,  /* A number, when tacked on to the end of a string guarantees a unique ID for the '«SCRIPT»' tag for the imported 'js. */ 
      _sSrcUri, /* The URI of the last JavaScript 'js' file imported by this utility.                                                  */
      _this = {

      dpnImporter: function(_thisFromEle){
          if (_thisFromEle.readyState) {                                    /* IE will respond to the 'onreadystatechange  */
              if (_thisFromEle.readyState === 'complete') {                 /* event firing and will make available the    */
                  _thisFromEle.anon = function(){                           /* 'readyState' property on the tag concerned. */
                      if (typeof lm !== 'undefined') {                      /* Check that JS (ie LMLibrary) is now there.  */
                          if (_thisFromEle.id.indexOf('eScriptId')===-1) {  /* Also, ensure this is the 1st time we add the*/
                              addJS(_thisFromEle.id);                       /* script and that subsequent event trips do   */
                              _thisFromEle.id= 'eScriptId' + ids++;         /* result in repeat additions of same script.  */
                          }   
                      }
                      else {
                          setTimeout(arguments.callee, 500);                /* LMlibrary hasn't been detected so test again*/
                      }
                  }();
              }
          } /* End if '_thisFromEle.readyState' exists */ 
          else {
              if (_thisFromEle.id.indexOf('eScriptId')===-1) {  /* Also, ensure this is the 1st time we add the*/
                  addJS(_thisFromEle.id);                       /* script and that subsequent event trips do   */
                  _thisFromEle.id= 'eScriptId' + ids++;         /* result in repeat additions of same script.  */
              } 
          }
      }, /* End method 'dpnImporter()' 'dependencyImporter()' */
      dpnNoEventSupport: function(sId){
        _sSrcUri = sId || _sSrcUri; /* rely on closure if call made into this method and no 'sId' supplied. */
        var eleScr;
          try 
          {
              eleScr = document.getElementById(_sSrcUri);
              if (eleScr === null)
              {
                  setTimeout(arguments.callee,10); /* Repeat poll (every 10s) to pick up added tag until its picked up .*/ 
              }
              else
              { 
                 if ( !(eleScr.onload || eleScr.onload) ) /* Bad news: the browser we are using doesn't support 'onload'   */ 
                 {                                        /* or 'onreadystate' change events so we'll have to poll to      */
                     if (typeof lm === 'undefined')
                     {
                         setTimeout(arguments.callee,5);
                     } /* repeatedly and test manually.     */
                     else 
                     {
                        addJS(_sSrcUri);
                     }
                 }
              }
          } 
          catch(Err) { }
        
      }/* End method 'dpnNoEventSupport()' 'dpnNoEventSupport()' */
  };
  return _this;
}(); /*[JF] END Self-invoking (for namespacing purposes) 'addJSnotifier()' function */

/*
* Description: Include the lm library - important
* [JF] 2009-09-23 Added in a polling mechanism ascertaing the readiness of the loaded-ness of LM Library; also
* [JF]            ensured that now 'addJS()' (to bring in 'EnhancedMap.js') is only called when we KNOW
* [JF]            LM Library is loaded; should eradicate all IE errors "Line 83: Error lm is 'undefined'".
*/
if( (typeof lm!='object') || (typeof lm == 'object' && !lm.loaded) ){       
    document.write('\u003Csc' + 'ript type="text/javascript" src="' + frontierURL + '/lm.js?skin=' + frontierSkin + 
                   '" id="http://cdn.lastminute.com/site/enhancedMap.js?skin=engb.bmibaby" onload="addJSnotifier.dpnImporter(this);" onreadystatechange="addJSnotifier.dpnImporter(this);"' + '>\u003C/sc' + 'ript>');
    document.write('\u003Csc' + 'ript type="text/javascript" src="' + frontierURL + '/lm_recently_search_template_title.js?skin=' + frontierSkin + '">\u003C/sc' + 'ript>');
    addJSnotifier.dpnNoEventSupport('http://cdn.lastminute.com/site/enhancedMap.js?skin=engb.bmibaby');
}

// get the computed styles on an element 
function getStyle(el,styleProp)
{
if(el){
    if (el.currentStyle)
        var y = el.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
    return y;
    }
}

// get the computed width of an element 
function getElementWidth(item) {
    if (typeof item.clip !== "undefined") {
        return item.clip.width;
    } else {
        if (item.style.pixelWidth) {
            return item.style.pixelWidth;
        } else {
            return item.offsetWidth;
        }
    }
}


/*
* Description - Legacy onload function to use lm library addEvent
*/
function SafeAddOnload(f){  
    lm.addEvent({fn:f});
}

/*
* Description: Cookie read and create, and query string read param functions below
*/
function createCookie(name, value, days) {
    lm.cookie.create({name: name, value: value, expire: days}); 
}

function readCookie(name){
    if (lm.cookie && lm.cookie[name]) {     
        return lm.cookie[name];     
    } else {
        return '0';
    }
}

function readQueryString(param) {
    if (lm.querystring[param]) {
        return lm.querystring[param];
    } else {
        return false;       
    }
}

/*
* Define a random number variable. Used as a param to js ads in master banners 
*/
var randNum = new Date().getTime();


/*
* Description: 
*/
function RTeCollector(strParam) {var intHeight = 460; var intWidth = 640; var intTop= ((screen.height/2)-(intHeight/2)); var intLeft= ((screen.width/2)-(intWidth/2)); var strFeatures='toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,height='+intHeight+',width='+intWidth+',top='+intTop+',left='+intLeft;var winEcollector = window.open('http://ecollector.responsetek.com/eCollector.asp?' + strParam, 'eCollector', strFeatures); }
function RenderPopup(windowsource,windowname,width,height,scrollbars,directories,location,menubar,status,toolbar,resizable) {  var windowfeatures = 'width=' + width +  ',height=' + height + ',directories=' + directories +  ',location=' + location + ',menubar=' + menubar +  ',scrollbars=' + scrollbars + ',status=' + status +  ',toolbar=' + toolbar + ',resizable=' + resizable;  window.open(windowsource, windowname, windowfeatures);  }
function LMN_showhidelayer(lyrName, show) { if (document.getElementById) {var obj = lm.e(lyrName); obj.style.display = show ? "block" : "none"; } else if(document.all) {document.all[lyrName].style.display = show ? "block" : "none";} else if(document.layers) {document.layers[lyrName].display = show ? "block" : "none";}}
function isValidEmail(emailAddress) {var atIndex = emailAddress.indexOf('@');var dotIndex = emailAddress.indexOf('.',atIndex);if( (0 < atIndex) && (atIndex < dotIndex) && (dotIndex < emailAddress.length-1) ) {var firstChar = emailAddress.charAt(0); if( (firstChar >= 'a' && firstChar <= 'z') || (firstChar >='A' && firstChar <= 'Z') || (firstChar >= '0' && firstChar <='9') ) { for (var i=1, j = emailAddress.length; i < j; ++i) {  if(emailAddress.charCodeAt(i) <= 0x20){  if(emailAddress.charAt(i) == ' ') {   alert("There are no spaces allowed in your email address"); }  else { alert("The character \"" + emailAddress.charAt(i) + "\" is not allowed in your email address");   }  return false;  }   }  return true;     }   alert("The first character in your email address, \"" + firstChar + "\" is not allowed"); } alert("Please enter a full email address"); return false; }

// Function used on travel/flights/deals section pages to populate the flights search form
function prePopulate(dep,dest,airline) {
    if (document.getElementById) {
        var fieldsId = ['departurePoint','destination','airline'];
        var formField;      
        for(var i=0, j=fieldsId.length; i < j; i++) {
            if(formField = lm.e(fieldsId[i])) {             
                if(formField.type == 'select-one') {                    
                    for (var x=0, y=formField.length; x < y; x++) {
                        if(formField.options[x].text == dep || formField.options[x].text == airline) { 
                            formField.selectedIndex = 1;
                        }                           
                        if (!(airline)) {
                            formField.selectedIndex = 0; 
                        }
                    }               
                }               
                if (formField.type == 'text') { 
                    formField.value = dest; 
                }
            }
        }
    }
}



/*
* Description: View product images thumbnail as larger image - on UI details pages
*/
function thumbnailSwitch(targetId,imageSrc,caption){
    lm.e(targetId).src = imageSrc;  
    if (lm.e(targetId + 'Caption')) {
        lm.e(targetId + 'Caption').innerHTML = caption;
    }
}

/*
* Toggle popups
*/
function togglePopup(obj){  

    if(typeof obj == 'object' && obj.href != undefined) 
        var bubbleContainer = lm.e(obj);
    else if(typeof obj == 'string' && lm.e(obj)) {
        var bubbleContainer = lm.e(obj);
        lm.styles(bubbleContainer, {visibility:'hidden', left:-1000, top:-1000});
        return true
    }
    else return false;


    if(obj.href){ bubbleContainer = lm.e(obj.href.split('#')[1])};
    var masterContainer = lm.e('master_center');
    var positioningDiv = lm.e('page_content');
    var objParent = obj;
    
    do{
        objParent = objParent.parentNode
        currentPosition = getStyle(objParent,'position')
    }
    while((currentPosition != 'relative'  && currentPosition != 'absolute') && objParent != document.body)
    
    positioningDiv = objParent
    var iframeId = 'underIframe' + obj.href.split('#')[1]
    var popupsOnScreen = lm.getElementsBy({tagName:'div', className:'bubbleText', filter:function(item){
            return (item.style.visibility=='visible')
        }
    }); 
    var zInd = (popupsOnScreen.length) ? popupsOnScreen[popupsOnScreen.length-1].style.zIndex+1 : Math.floor(Math.random() * 1000);
    lm.addEvent({e:bubbleContainer.getElementsByTagName('a')[0], eT:'click', fn:function(e){        
        lm.styles(bubbleContainer, {visibility:'hidden', left:-1000, top:-1000});
        masterContainer.style.zIndex = '2';
        if (lm.e(iframeId)) positioningDiv.removeChild(lm.e(iframeId));     
        if (!e) e = window.event;
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            e.returnValue = false;                                                           
        }
    }});
    var isIE6 = /msie ([0-6]{1,}[\.0-9]{0,})/.test(navigator.userAgent.toLowerCase());
    var leftPosition = lm.getLeft(obj) - lm.getLeft(positioningDiv) - (getElementWidth(obj)/2);
    var topPosition = lm.getTop(obj) - lm.getTop(positioningDiv) - bubbleContainer.offsetHeight;
    
    if ( !lm.e(iframeId) && isIE6 && navigator.userAgent.indexOf('opera')==-1) {        
        new lm.element.block({p: positioningDiv, tagName: 'iframe', id: iframeId, frameBorder: '0', scrolling: 'no', src: 'javascript:false;'})
        var iframeReference = lm.e(iframeId);       
        lm.styles(iframeReference, {
            position: 'absolute',
            left: leftPosition, 
            top: topPosition,
            width: bubbleContainer.offsetWidth,
            height: bubbleContainer.offsetHeight,
            zIndex: zInd - 1,
            filter: 'alpha(opacity=0)'
        });         
    }
    masterContainer.style.zIndex = '25';

    lm.styles(bubbleContainer, {visibility:'visible', left: lm.getLeft(obj) - lm.getLeft(positioningDiv) - (getElementWidth(obj)/2), top:lm.getTop(obj) - lm.getTop(positioningDiv) - bubbleContainer.offsetHeight, zIndex: zInd});
}

function togglePopupLeft(obj){  
    togglePopup(obj);
}

// Toggle the display of the bubble popup       
function togglePopupBranded(obj,show){
    var offSetFromMouse = [];
    offSetFromMouse[0] = 231;
    offSetFromMouse[1] = 145;
    var divHeight = 0;
    var selects = lm.getElementsBy({parentNode:'page_content', tagName:'select'});  
    if (selects.length) {
        if (show && selects[0].style.visibility != 'hidden'){
            for(var i=0, j = selects.length; i < j; i++) {
                selects[i].style.visibility = 'hidden';
            }
        }       
        else if ( !(show)) {
            for(var i=0, j = selects.length; i < j; i++) {
                selects[i].style.visibility = '';   
            }
        }
    }   
    if (obj.href) {
        var divCont = obj.href.split('#')[1];
        divCont = lm.e(divCont);
        divCont.style.position = 'absolute';
        divCont.style.visibility='visible';
        if (show){
            lm.e('master_center').style.zIndex='12';
            if (divCont.offsetHeight){
                divHeight = divCont.offsetHeight;
            } else if (divCont.style.pixelHeight){
                divHeight=divCont.style.pixelHeight;
            }   
            var curleft = curtop = 0;
            if (obj.offsetParent) {
                curleft = obj.offsetLeft;
                curtop = obj.offsetTop;
                while (obj = obj.offsetParent) {
                    curleft += obj.offsetLeft;
                    curtop += obj.offsetTop;
                }
            }       
            divCont.style.top=(curtop-offSetFromMouse[1]-divHeight)+'px';
            divCont.style.left=(curleft-offSetFromMouse[0])+'px';
        } else {
            lm.e('master_center').style.zIndex='2';
            divCont.style.left='-1000em';
            divCont.style.top='-1000em';            
        }
    } else {
        divCont = lm.e(obj);    
        divCont.style.position='absolute';
        divCont.style.left='-1000em';
        divCont.style.top='-1000em';
    }
}

/* 
* Description - Price formatter functions
*/

function currencyStrip(amount) {
    if (amount.constructor.name == "String") return parseFloat(amount.match(/(\d{1,3},?)+([,|.]\d+)?/g)[0].replace(/,/g,''));
}

function currencyFormat(amount, currencyCode, locale, decimalPoints, currencyRoundUp) {
    var decimalPoints = decimalPoints || 0;
    var currencyRoundUp = currencyRoundUp || false;
    var amount = (currencyRoundUp) ? amount + '' : parseFloat(amount).toFixed(decimalPoints); 
    if (currencyRoundUp){
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(amount)) {
            amount = amount.replace(rgx, '$1' + ',' + '$2');
        }       
    }

    var currencyCodes = {
        'EUR' : "&euro;",
        'GBP' : "&pound;",
        'INR' : "Rs",
        'HKD' : "HKD",
        'AUD' : "AUD",
        'SGD' : "SGD"};
 
    switch(locale) {
    case 'en_GB':
        return currencyCodes[currencyCode] + amount;
        break
    case 'es_ES':       
    case 'fr_FR':
        return amount + ' ' + currencyCodes[currencyCode];
        break
    case 'en_IN':
    case 'it_IT':
    case 'en_HK':
    case 'en_AU':
    case 'en_SG':
        return currencyCodes[currencyCode] + ' ' + amount;
        break
    default:
        return amount + '?';
    }
}

/*
* Description : Airport code finder
*/
var originOrDestination = 'D'; //Updates the airport name field in Search with the name found by the service
//Takes the value entered and send this to the page calling the service
function findDestination(url,field) {
    var airportCodes = lm.e(field);
    var value = (airportCodes)? airportCodes.value : '';
    var urlString = url;        
    if (urlString.indexOf('?') == -1) {
        var location = '?location=';
    }       
    else {
        var location = '&'+'location='; 
    }       
    var url = urlString + location + value + '&'+'fieldName=' + field;
    window.open(url,'findAiports','width=300,height=300,resizable=0,status=yes,scrollbars=yes');
    originOrDestination = 'D'
}

/* 
 * Description: Replace the value of the field with the value found by the service
 */
function setDestination(text, field) {
    lm.e(field).value = text;
}

/*
* Description : calendar positioning hack
*/
var hijackShowCalendarTimer=-1;var calendarIframe=false;function hijackShowCalendar(){if(typeof showCalendar=="function"){clearTimeout(hijackShowCalendarTimer);showCalendar=function(e){var o=(typeof event!="undefined")?event.srcElement:e.target;var _3=lm.e("cIframe");if(!calendarIframe){_3.style.visibility="hidden";calendar.show(0,0);calendarIframe={left:lm.getLeft(_3),top:lm.getTop(_3)};_3.style.visibility="visible";}calendar.show((lm.getLeft(o)-calendarIframe.left)+o.width+5,lm.getTop(o)-calendarIframe.top);};}else{hijackShowCalendarTimer=setTimeout("hijackShowCalendar()",500);}}hijackShowCalendar();function stopHijackShowCalendarLoop(){if(typeof showCalendar != "function" && hijackShowCalendarTimer != -1){clearTimeout(hijackShowCalendarTimer);}}if(typeof calendar=="object"){var hijackOldOnload = window.onload; if(typeof hijackOldOnload == "function"){window.onload=function(){stopHijackShowCalendarLoop(); hijackOldOnload(); } ; } else {window.onload=stopHijackShowCalendarLoop;}}


/*
* Description : accent strip library
*/
function stripVowelAccent(str, str_type) {var s=str;   var stripped=str; var rExps=[ /[\xC0-\xC5]/g, /[\xE0-\xE5]/g,   /[\xC8-\xCB]/g, /[\xE8-\xEB]/g, /[\xCC-\xCF]/g, /[\xEC-\xEF]/g, /[\xD2-\xD6]/g, /[\xF2-\xF6]/g, /[\xD9-\xDC]/g, /[\xF9-\xFc]/g,/[\xD1]/g, /[\xF1]/g, /[\xC7]/g, /[\xE7]/g ]; var repChar=['A','a','E','e','I','i','O','o','U','u','N','n','C','c']; for(var i=0; i<rExps.length; i++) { stripped=stripped.replace(rExps[i],'_'); s=s.replace(rExps[i],repChar[i]); } return s; }

/*
* Description : adds ratefinder popunder to hotels, flights and dp searches
*/





/* 
* Description: link the radio buttons for the search box categories in IE
*/ 

if (window.addEventListener || window.attachEvent) {
    var fAddOnLoad = function() {
        
        var inputs = document.getElementsByTagName('input');
        for(var i = 0;i < (inputs.length -1); i++){
            var input = inputs[i];
            if(input.type=='radio' && input.checked==false && input.name=='' && input.parentNode.tagName=='A'){
                input.onclick = function(){ 
                    window.location = this.parentNode.href;
                    this.checked = true;
                }
            }
        }
            
            
            
    }
    if (window.attachEvent) window.attachEvent("onload", fAddOnLoad); // IE
    else window.addEventListener("load", fAddOnLoad, false); // W3C compliant
}

/*
* Description : adds a js file to head of page - specifically needed for multimap
*/
function addJS(src) {
    var pageHead = document.getElementsByTagName('head')[0];
    var mapScript = document.createElement('script');
    mapScript.setAttribute('type','text/javascript');
    mapScript.setAttribute('src',src);
    pageHead.appendChild(mapScript);
}
/* [JF] 2009-09-23 Now 'addJS()' called by 'onreadystatechange' in the '«SCRIPT»' tag that brings in LMlibrary so no  need */
/*                 here to have a:                                                                                         */
/*                 addJS(frontierProtocol+'://'+frontierHTTPHost+'/...site../enhancedMap.js?skin=engb.lastminute.com');*    */

            function addMMKey() {
                addJS('http://clients.multimap.com/API/maps/1.2/lastminute_api?locale=en-gb');
            }

function clearField(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}


atags = document.getElementsByTagName('A')

for(i=0; i < atags.length;i++){
    atag = atags[i]
    if(atag.href.indexOf('hotels-arbo.html') > -1){
        atag.href = atag.href.replace('hotels-arbo.html','hotels-browse.html')
    }
}
// --- [end prdpcthpb0507:4003 - /site/generic.js - Feb 9, 2010 2:23 pm GMT - akamai,pcth0308,pct0410 - qIfOAgqoQ1UAAF@RzEgAAGAM - cache 1800 ] ---
