//#################### AJAX FUNCTIONS ###########################################

// OLD, NEEDS TO BE REPLACED !
/**
 * Is used to perform HTTP updates to a server. Any result data is stored in a DIV element.
 *
 * @param url The URL update to call.
 * @deprecated param div The id of the DIV to store any returned data from the HTTP call.
 * @deprecated param postScript Specifies Javascript to run when a response has been received. Can be empty.
 */
function httpUpdate(url) {
	var http = getHTTPObject(); //we create the HTTP Object

	http.open("GET", url + '&random=' + Math.random(), true);	//a random parameter is added to prevent the browser from using cached data
	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			//deprecated: document.getElementById(divId).innerHTML = http.responseText;	//stores the returned update data
			eval(http.responseText);	//executes the returned data as Javascript
		}
	}

	http.send(null);
}

/**
 * Is used to perform XML HTTP requests and receive HTTP data.
 */
function getHTTPObject() {
	var xmlhttp;
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		}
		catch (e) {
			xmlhttp = false;
		}
	}

	return xmlhttp;
}

//#################### UTILITY FUNCTIONS ########################################

/**
 *This function checks if an array contains a specific string or not.
 * @param array The array to search in
 * @param stringToCheck the string to check for
 * @returns true if it does and false otherwise.
 *
 */
function arrayContains(array, stringToCheck) {
	for (var i in array) {
		if (array[i] == stringToCheck) {
			return true;
		}
	}

	return false;
}

function popUp(url, height, width) {
    if(height && width){
        var newwindow = window.open(url,'','height='+height+',width='+width+',resizable=yes,scrollbars=yes');        
    }  else {
        var newwindow = window.open(url,'','height=600,width=770,resizable=yes,scrollbars=yes');
    }
    if (window.focus) {
		newwindow.focus()
	}
}

function getParams() {
	var paramStr = document.location + '';
	paramStr = paramStr.split("?");

	var params = new Array;
	if (paramStr[1] != null) {
		var pairs = paramStr[1].split('&');
		for (var i=0; i < pairs.length; i++) {
			nameVal = pairs[i].split('=');
			params[nameVal[0]] = unescape(nameVal[1]);
		}
	}
	
	return params;
}

function toggleSH(indiv, lcase){
	var theDiv = $(indiv);
    var s = new String(i18Show);

	if(theDiv){
		if(theDiv.innerHTML.toUpperCase() == s.toUpperCase()){
		  if(lcase == '1'){
		      theDiv.innerHTML = toLCase(i18Hide);
		  }else{
		      theDiv.innerHTML = i18Hide;
		  }
		} else {
		  if(lcase == '1'){
		      theDiv.innerHTML = toLCase(i18Show);
		  }else{
		      theDiv.innerHTML = i18Show;
		  }
		}
	}
}

/*
    function tsHFull
    
    indiv : the div/span/id that contains the text to switch
    wS: name of the variable containing the "show" text
    wH: name of the variable containing the "hide" text
 */
function tSHFull(indiv, wS,wH){
    if($(indiv)){
        if(wS == $(indiv).innerHTML){ // we know the content contains "show"
            $(indiv).innerHTML = wH;
        } else {
            $(indiv).innerHTML = wS;
        }
    }
}

function toLCase(str){
    s = new String(str);
    return(s.toLowerCase());
}

function populateFields(params, parArr){
   for(var i=0;i<parArr.length;i++){
	   if(params[parArr[i]]){
	       Form.Element.setValue(parArr[i],params[parArr[i]]);
		}
	}
}

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 showPopup(){
	var showTrue = Cookie.get("indexnewsletter");
    if(showTrue == null)
		displayPopup();
	Cookie.set("indexnewsletter", "true", 7);
}

function showComp(compName){
   var showTrue = Cookie.get(compName);
	if(showTrue == null){
        displayComp(compName);
	Cookie.set(compName, 'true', 7);
    }
}

function displayComp(compName){
   if ($(compName)) $(compName).show();
}

function displayPopup(){
	if ($('lff')) $('lff').show();
}


function hideSel(){
    $$('select').each( function(sel) { sel.hide() } );
}

function showSel(){
    $$('select').each( function(sel) { sel.show() } );
}

function getHint(){
    $('forgotDiv').hide();
    $('forgotDivText').hide();
    $('hintDiv').show();
    $('hintContent').hide();
}
function hintMe(){
    if (validateLoginEmailHelp($('loginEmailHint').value, 'loginEmailHintError')) {
        var url = 'myAccountAjax.jsp';
        var pars = 'action=getPasswordHint' + '&email=' + $('loginEmailHint').value;
        var myAjax = new Ajax.Request(
                    url, {
                        method: 'post',
                        parameters: pars,
                        onComplete: showHint,
                        asynchronous: true
                       }
        );
        $('hintContent').show();
        $('hintProgress').innerHTML = ajaxLoading;
    }

}

function showHint(originalResponse){
    var response = originalResponse.responseText;
    if (response == 'noHint') {
        $('hintValue').innerHTML = '<span style="color:red;">' + noHintFound + '</span>';
    }
    else {
        $('hintValue').innerHTML = '<span style="color:#6bba65;">' + response + '</span>';

    }
    $('hintDiv').hide();
    $('hintProgress').innerHTML = '&nbsp;';
    
}

function forgotPassword(){
    $('hintDiv').hide();
    $('hintContent').hide();
    $('forgotDivText').hide();
    $('forgotDiv').show();
}   

function getPassword(){
    if (validateLoginEmailHelp($('loginEmailForgot').value, 'loginEmailForgotError')) {
        var url = 'myAccountAjax.jsp';
        var pars = 'action=resendPassword' + '&email=' + $('loginEmailForgot').value;
        var myAjax = new Ajax.Request(
                    url, {
                        method: 'post',
                        parameters: pars,
                        onComplete: showFP,
                        asynchronous: true
                       }
        );
        $('forgotDivText').show();
        $('forgotDivText').innerHTML = ajaxLoading;
    }
}

function showFP(originalResponse){
    $('forgotDivText').innerHTML = checkMailForPassword;
    $('forgotDiv').hide();
}

function cartLogin(){
    if (validateLoginEmail() && validateLoginPassw()) {
        var url = 'myAccountAjax.jsp';
        var pars = 'action=login' + '&email=' + $('loginEmail').value + '&password=' + $('loginPassword').value;
        var myAjax = new Ajax.Request(
                    url, {
                        method: 'post',
                        parameters: pars,
                        onComplete: showCartItineraryLoginStatus,
                        asynchronous: true
                       }
        );
        $('cartLoginText').show();
        $('cartLoginText').innerHTML = ajaxLoading;
    }
}

function showCartItineraryLoginStatus(originalResponse){
    if (originalResponse.responseText == '0') {
        $('signInNotValid').show();
    }
    else {
        gol(document.location)
    }
    $('cartLoginText').hide();
}

function gup( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ) {
	if (name == 'numberOfRooms') {
		return 1;
	}
    return "";
  }
  else {
    if (name == 'homeLeaveDay' || name == 'destLeaveDay') {
        if (results[1] > 0 && results[1] < 10) {
            if(results[1].substring(0,1) != "0"){
                results[1] = '0' + parseInt(results[1]);
            }
        }
    }
    return results[1];

  }
}

function goTo(url){
	setTimeout("gol('"+url+"')",1000);
}

function gol(url){
	document.location.href = url;
}

function trimText(instr, size){
    if(instr.length > size){
        return(instr.substring(0,size) + '...');
    } else {
        return(instr);
    }
}

String.prototype.format = function()
{
    var str = this;
    for(var i=0;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    var testForInstallment = str.indexOf('<span class="refcolor bold">');
    if(testForInstallment > -1){
        return(str.substring(0,testForInstallment) + '<br/>' + str.substring(testForInstallment, str.length));
    }
    return str;
}

function showAllH(maxcount){
    for(i=1;i<maxcount;i++){
	   $('bedFare'+i).show();
	}
	$('shH').hide();
	//$('hiH').show();
}

function hideAllH(maxcount){
    for(i=1;i<maxcount;i++){
	   $('bedFare'+i).hide();
	}
	$('hiH').hide();
	$('shH').show();
}

function showAllC(maxcount){
    for(i=1;i<maxcount;i++){
	   $('carFare'+i).show();
	}
	$('shC').hide();
	//$('hiC').show();
}

function hideAllC(maxcount){
    for(i=1;i<maxcount;i++){
	   $('carFare'+i).hide();
	}
	$('hiC').hide();
	$('shC').show();
}

function toggleLB(inL){
	var s1 = $('sh_'+inL).innerHTML;
	var s2 = $('sh_fd_'+inL).innerHTML;
	var cL = document.getElementById('ed_'+inL);
	if(cL){
		if(s1 == i18Show && s2 == i18Show){
			Element.setStyle(cL, {borderTop:'8px solid #ebebeb'});
		} else {
			Element.setStyle(cL, {borderTop:'0px'});
		}
	}
}

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
  }
};

function toggleId(id){
    if($(id)){
        if($(id).visible()){
            $(id).hide();
        } else {
            $(id).show();
        }
    }
}

var activex = ((navigator.userAgent.indexOf('Win')  != -1) && (navigator.userAgent.indexOf('MSIE') != -1) && (parseInt(navigator.appVersion) >= 4 ));
var CantDetect = ((navigator.userAgent.indexOf('Safari')  != -1) || (navigator.userAgent.indexOf('Opera')  != -1));

function oopsPopup() {
    if((navigator.language && navigator.language.indexOf("ja") != -1) || (navigator.systemLanguage && navigator.systemLanguage.indexOf("ja") != -1) || (navigator.userLanguage && navigator.userLanguage.indexOf("ja") != -1)) {
        var URLtoOpen = "http://download.skype.com/share/skypebuttons/oops/oops_ja.html";
    } else {
        var URLtoOpen = "http://download.skype.com/share/skypebuttons/oops/oops.html";
    }
	var windowName = "oops";
	var popW = 540, popH = 305;
	var scrollB = 'no';
	w = screen.availWidth;
	h = screen.availHeight;
	var leftPos = (w-popW)/2, topPos = (h-popH)/2;
	oopswindow = window.open(URLtoOpen, windowName,'width=' + popW + ',height=' + popH + ',scrollbars=' + scrollB + ',screenx=' +leftPos +',screeny=' +topPos +',top=' +topPos +',left=' +leftPos);
	return false;
}

if(typeof(detected) == "undefined" && activex) {
    document.write(
        ['<script language="VBscript">',
        'Function isSkypeInstalled()',
        'on error resume next',
        'Set oSkype = CreateObject("Skype.Detection")',
        'isSkypeInstalled = IsObject(oSkype)',
        'Set oSkype = nothing',
        'End Function',
        '</script>'].join("\n")
    );
}

function skypeCheck() {
    if(CantDetect) {
        return true;
    } else if(!activex) {
        var skypeMime = navigator.mimeTypes["application/x-skype"];
        detected = true;
        if(typeof(skypeMime) == "object") {
            return true;
        } else {
            return oopsPopup();
        }
    } else {
        if(isSkypeInstalled()) {
            detected = true;
            return true;
        }
    }

    detected = true;
    return oopsPopup();
}

function loadDetection() {
    if(document.getElementById && document.getElementsByTagName) {
        if (window.addEventListener) window.addEventListener('load', addDetection, false);
        else if (window.attachEvent) window.attachEvent('onload', addDetection);
    }
}

function addDetection() {
    var pageLinks = document.getElementsByTagName("a");
    for (var i=0; i < pageLinks.length; i++) {
        if(pageLinks[i].childNodes[0] && pageLinks[i].childNodes[0].src) {
            if((pageLinks[i].childNodes[0].src.indexOf('download.skype.com\/share\/skypebuttons') != -1 || pageLinks[i].childNodes[0].src.indexOf('mystatus.skype.com') != -1) && (typeof(pageLinks[i].onclick) == "undefined" || pageLinks[i].onclick == null)) {
                pageLinks[i].onclick = function sChk() { return skypeCheck(); }
            }
        }
    }
}

function validateAwaitingDirect(paymentId) {
    var myAjax = new Ajax.PeriodicalUpdater('', '3ds.jsp', {
        method: 'get',
        parameters: 'adpid=' + paymentId,
        frequency: 5,
        decay: 0,
        onSuccess:  function(transport) {
            if (transport.responseText.match('Direct_Payment_OK')) {
                reloadPage();
            }
            else if (transport.responseText.match('Direct_Payment_FAILED')) {
                myAjax.stop();
            }
            else if (transport.responseText.match('Direct_Payment_AWAITING')) {}
            else {
                myAjax.stop();
            }
         },
        onFailure: function(){ myAjax.stop(); }
    });
}

/**
 * Is used to check if all the data for a Payment has been filled before submitting.
 *
 * @param ccFormValidation The validate object for the pay form.
 * @param payButtonId The id of the payment button.
 */
function prePaymentCheck(ccFormValidation, payButtonId) {
	var noError = false;
	if (ccFormValidation.validate(true, payButtonId)) {	//if the CC payment form is valid
		noError = true;
		var payButton = document.getElementById(payButtonId);
		payButton.disabled = "disabled";	//disables the Pay-button to avoid double payment at double-click
	}

	return noError;
}

//This function takes a string of the format 20040923 and converts it to a date
function stringToDate(dateString){
  dateString = new String(dateString);
	var year = dateString.substring(0,4);
	var month = dateString.substring(4,6);
	var day = dateString.substring(6,8);

	month = removeFirstZero(month);
	day = removeFirstZero(day);
	month = month -1;

	var myDate = new Date(year, month, day);
	return myDate;
}

/**
 * Opens a popup window with specified url, width and height.
 */
function openWindow(url,width,height) {
	window.open(url,"Help","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width="+width+",height="+height+"");
}

loadDetection();

function showId(ele){
    if($(ele)){
        $(ele).show();
    }
}

function hideId(ele){
    if($(ele)){
        $(ele).hide();
    }
}

// posts to calendar.jsp from index page button
function toCal(extPartner,val){
    var url = "match.jsp?waitURL=calendar.jsp&&matchURL=wait.jsp&waitMessage=waitSearch&matchParameter=homeCity&matchParameter=destCity&homeLeaveMonth=" + departDate.getFullYear() + padDate(departDate.getMonth()+1) + "&extPartner=" + extPartner + "&numberOfRooms=" + $('numberOfRooms').value + "&destLeaveDay=" + padDate(returnDate.getDate());
    url += "&isReturn=" + isReturn + "&paxAdults=" + $('paxAdults').value + "&homeCity=" + $('homeCity').value + "&view=" + view + "&paxKids=" + $('paxKids').value;
    url += "&destLeaveMonth=" + returnDate.getFullYear() + padDate(returnDate.getMonth() + 1) + "&destCity=" + $('destCity').value + "&paxTeens=" + $('paxTeens').value + "&specificAirline=" + checkSpecificAirline() + "&paxInfants=" + $('paxInfants').value;
    url += "&homeLeaveDay=" + padDate(departDate.getDate());
    if($('extPartner')){
        url += "&extPartner=" + $('extPartner').value;
    }
    if(val.validate(true)){
        goTo(url);
    }
}


function padDate(m){
    if(m < 10){
        return('0'+m);
    }
    return(m);
}

function checkSpecificAirline(){
    if($('specificAirline')){
        return($('specificAirline').value);
    }
    return '';
}

function updatePri(){
	if(priceHandler){
		priceHandler.updatePrices();
	}
}

function showUnconfirmedLightbox(){
    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScroll();
    $('overlayCI').style.height = arrayPageSize[1]*1.3+'px';
    $('overlayCI').style.offsetWidth = parseInt(arrayPageSize[2]-arrayPageScroll[0]) +'px';
    $('overlayCI').show();
    var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 15);
    $('unconfirmedCI').style.top = lightboxTop + 'px';
    $('unconfirmedCI').style.left = parseInt(arrayPageSize[0]/2 -180) + 'px';
    $('unconfirmedCI').show();		
}

// GOOGLE AFS

function GetParam(name)
 {
     var match = new RegExp(name + "=(.+)[&]","i").exec(location.search);
     if (match==null)
     {
         match = new RegExp(name + "=(.+)","i").exec(location.search);
     }

     if (match==null)
     {
         return null;
     }

     match = match + "";
     result = match.split(",");
     return result[1];
 }

function google_afs_request_done(google_ads)
  {
      /*
       * Kontrollera att det verkligen finns annonser att visa.
       */
      var google_num_ads = google_ads.length;
      if (google_num_ads <= 0)
      {
          return;
      }

      var wideAds = "";   // html-text f�r bred annons
      var narrowAds = "";   // html-text f�r smal annons

      for(i = 0; i < google_num_ads; i++)
      {
          if (google_ads[i].type=="text/wide")
          {
              // render a wide ad
              wideAds+='<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
                      google_ads[i].url + '\';return true;" ' +
                      'onmouseout="javascript:window.status=\'\';return true;" ' +
                      'href="' + google_ads[i].url + '">' +

                      '<span class="ad_line1">' + google_ads[i].line1 + '</span></a><br>' +

                      '<span class="ad_text">' + google_ads[i].line2 + '</span><br>' +

                      '<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
                      google_ads[i].url + '\';return true;" ' +
                      'onmouseout="javascript:window.status=\'\';return true;" ' +
                      'href="' + google_ads[i].url + '">' +

                      '<span class="ad_url">' + google_ads[i].visible_url + '</span><br><br></a>';
          }

          else
          {
              // �terger en smal annons
              narrowAds+='<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
                      google_ads[i].url + '\';return true;" ' +
                      'onmouseout="javascript:window.status=\'\';return true;" ' +
                      'href="' + google_ads[i].url + '">' +

                      '<span class="ad_line1">' + google_ads[i].line1 + '</span></a><br>' +

                      '<span class="ad_text">' + google_ads[i].line2 + '</span><br>' +

                      '<span class="ad_text">' + google_ads[i].line3 + '</span><br>' +

                      '<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
                      google_ads[i].url + '\';return true;" ' +
                      'onmouseout="javascript:window.status=\'\';return true;" ' +
                      'href="' + google_ads[i].url + '">' +

                      '<span class="ad_url">' + google_ads[i].visible_url + '</span><br><br></a>';
          }
      }

      if (narrowAds != "")
      {
          narrowAds = '<a style="text-decoration:none" ' +
                      'href="http://services.google.com/feedback/online_hws_feedback">' +
                      '<span class="ad_header" style="text-align:left">Google-annonser</span><br><br></a>' + narrowAds;
      }

      if (wideAds != "")
      {
          wideAds = '<a style="text-decoration:none" ' +
                    'href="http://services.google.com/feedback/online_hws_feedback">' +
                    '<span class="ad_header" style="text-align:left">Google-annonser</span><br><br></a>' + wideAds;
      }

      // Skriv HTML f�r breda och smala annonser f�r r�tt <div>-element
      document.getElementById("wide_ad_unit").innerHTML = wideAds;
      document.getElementById("narrow_ad_unit").innerHTML = narrowAds;
  }


function showWaitLightbox(){
    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScroll();
    $('overlayCI').style.height = arrayPageSize[1]*1.3+'px';
    $('overlayCI').style.offsetWidth = parseInt(arrayPageSize[2]-arrayPageScroll[0]) +'px';
    $('overlayCI').show();

    var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 15);
    $('waitCI').style.top = lightboxTop + 'px';
    $('waitCI').style.left = parseInt(arrayPageSize[0]/2 -200) + 'px';
    $('waitCI').show();
}
