function getXMLHttpRequest(){
    var request = false;
    try{
        request = new XMLHttpRequest(); 
    }catch( err1 ){
        try{
            request = new ActiveXObject('Msxm12.XMLHTTP');
        }catch(err2){
            try{
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(err3){
                request = false;
            }
        }
    }
    //request.setRequestHeader('X_REQUESTED_WITH', "XMLHttpRequest");
    return request;
}

function getFileName(){
     
     //vars
     sMyUrl = window.location.href;
     sHostName = window.location.hostname;
     sAvoid = "index";
     sMySub2 = ".php";   
   
     if((iIndex = sMyUrl.indexOf(sMySub2)) > -1){ 
        if(sMyUrl.indexOf(sAvoid + sMySub2) < 0 ){ 
            return sMyUrl.substr(0, iIndex + sMySub2.length);
        } 
     } 
      return sMyUrl.substr(0, (sMyUrl.indexOf(sHostName) + sHostName.length));
     
}

function disableElement(sId, bDisable){

    var oObject = document.getElementById(sId);
    
    if(bDisable){
        oObject.setAttribute('disabled', 'disabled');
    } else{
        oObject.removeAttribute('disabled');
    }
    
}

function changeButtonImg(oSource, sPath){
    oSource.src = getFileName() + '/' + sPath;

}

function link_underline(iId, bUnderline){
    
    if(bUnderline){
        document.getElementById(iId).style.textDecoration = 'underline';
    } else {
        document.getElementById(iId).style.textDecoration = 'none';
    }

}


function getHostName(){
  sHostName = 'http://' + window.location.hostname;
  return sHostName;
}

function Set_Cookie( name, value, expires, path, domain, secure ){
    
    var today = new Date();
        today.setTime( today.getTime() );
    
        if ( expires ){
             expires = expires * 1000 * 60 * 60 * 24;
        }
        
    var expires_date = new Date( today.getTime() + (expires) );
    
        document.cookie = name + "=" +escape( value ) +
                        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
                        ( ( path ) ? ";path=" + path : "" ) + 
                        ( ( domain ) ? ";domain=" + domain : "" ) +
                        ( ( secure ) ? ";secure" : "" );

}

function Get_Cookie( check_name ) {

    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    
    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        a_temp_cookie = a_all_cookies[i].split( '=' );
        
        
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
    
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

function Delete_Cookie( name, path, domain ) {
 
  if ( Get_Cookie( name ) ) {
     document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function getFullWebSitePath(){
    return window.location.href;
}
  

function getUserWindowName(){

              var curdate = new Date();
              var hours = curdate.getHours(); 
              var minutes = curdate.getMinutes(); 
              var seconds = curdate.getSeconds();
       
              if(window.name == ''){
                 window.name =  (hours + '_' + minutes + '_' + seconds);
               }
            
            return window.name;
}

function blurThis(oObject){
    oObject.blur();
}

function onlydec(event){
    if (event.srcElement) {kc = event.keyCode;} else {kc = event.which;}
    if ((kc < 47 || kc > 57) && kc != 8 && kc != 0) return false;
 return true;
}

function checkIsHigher(oObject, iValue){
     oObject.value = (parseInt(oObject.value) > iValue || parseInt(oObject.value) < 0) ? iValue : oObject.value;
}

function echeck(str) {

        var at="@"
        var dot="."
        var lat=str.indexOf(at)
        var lstr=str.length
        var ldot=str.indexOf(dot)
        if (str.indexOf(at)==-1){
           //alert("Invalid E-mail ID")
           return false
        }

        if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
           return false
        }

        if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
            return false
        }

         if (str.indexOf(at,(lat+1))!=-1){
            return false
         }

         if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
            return false
         }

         if (str.indexOf(dot,(lat+2))==-1){
            return false
         }
        
         if (str.indexOf(" ")!=-1){
            return false
         }
         
         //TODO dopisac niedowzwolne litery

         return true                    
}

function validateDate(sDate){
        
      var sDate = sDate.replace(/^\s+|\s+$/g, '');
      var regExp = /^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})$/i;
        
      var matches = sDate.match(regExp);
      if(matches == null){
       return false;
      } else {
       return true;
      }
}

function checkAllCheckbox(sId, bCheck){
    
    if(bCheck){
        jQuery('#' + sId + ' :checkbox').attr('checked', 'true');
    } else {
        jQuery('#' + sId + ' :checkbox').removeAttr('checked');
    }

}
function checkDifferenceCheckbox(sId){
    
        jQuery('#' + sId + ' :checkbox').each(function(i){
          if(jQuery(this).attr('checked')){
                jQuery(this).removeAttr('checked');
            } else {
                jQuery(this).attr('checked', 'true');
          }
        });
}

function createMultipleBrowseFileButton(sDestinationId, sCountIdListener, sClass){
        
        var iCounter = parseInt(jQuery('#' + sCountIdListener).val());
        iCounter++;
        jQuery('#' + sCountIdListener).val(iCounter);
        var sFile = '<input type="file" name="file_browser_' + iCounter + '" id="file_browser_' + iCounter + '" value="" class="' + sClass +'" /><br />';
        jQuery('#' + sDestinationId).append(sFile);    
}


function doHoverEffectImg(oObject, sFormat){
    var sSrc = '';
    
    if(sFormat == undefined){
       sFormat = 'gif';
    }
    
    jQuery(oObject).hover(
        function () {
            sSrc = $(this).attr('src');
            sSrc = sSrc.replace('.' + sFormat ,'_hover.' + sFormat);
            $(this).attr('src', sSrc);
        }, 
        function () {
            sSrc = $(this).attr('src');
            sSrc = sSrc.replace('_hover.' + sFormat, '.' + sFormat);
            $(this).attr('src', sSrc);
        }
    );
}

function rememberCookiePath(sName){
    Set_Cookie((sName  + getUserWindowName()), getFullWebSitePath(), '', '/', '', '' );
} 

function checkIsRememberPathCookie(sName){

    if(Get_Cookie((sName  + getUserWindowName()))){
        jQuery("#back_referer_path").show();
    }
} 

function returnToSavedWebSitePathCookie(sName){
    window.location.href = Get_Cookie((sName  + getUserWindowName()));
    Delete_Cookie((sName  + getUserWindowName()), '/', '');
}

function secureNumber(fNumber){
	
	return Math.round(fNumber);
}

function setRoundNumber(fNumber, sType){
	
	if(sType == 'round'){
	   return Math.round(fNumber);
	} else if(sType == 'floor'){
		return Math.floor(fNumber);
	} else if(sType == 'ceil'){
		return Math.ceil(fNumber);
	} else {
		return Math.floor(fNumber);
	}
}

function getPercent(iCost, iPercent, bRound){
    var aData = new Array();
    
    if(iPercent == undefined){
       iPercent = 5; 
    }
    if(bRound == undefined){
    	bRound = false; 
    }
    
    aData[0] =  (iCost * iPercent)/100; 
    
    if(bRound){
    	/*var iDiff = aData[0]%1;
    	if(iDiff > 0){
    		alert(iDiff);
    		aData[0] = Math.round(aData[0] + iDiff);
    	}*/
    	aData[0] = Math.round(aData[0]);
    }
    
    aData[1] =  (iCost - (aData[0])); 
    
    
    return aData;
} 

function addToFavorites(){

     var sTitle = document.title; 
     var sUrl = window.location.href;
     
     //ie
     try{
          if(document.all){
            window.external.AddFavorite(sUrl, sTitle); 
            return false;
          }
     }catch(e){}
     
    //firefox 
    try{ 
         if (window.sidebar) {
             window.sidebar.addPanel(sTitle, sUrl, ""); 
             return false;
        }
     }catch(e){}
    
    //opera    
     try{ 
         if (window.opera && window.print){   
            var a = document.createElement('a');
                a.href=location.href;
                a.rel='sidebar';
                a.title=document.title;
                a.onclick=function() {
                    //return void(0); 
                  }
                a.click();
                /* this is bug for opera? who knows :)? it works
                   you need to trigger error to open favourite box   
                */
                var newErrorObj = new Error('', ''); 
         }   
      }catch(e){}

}

function validateTerm(sId){
    
    var sDate = jQuery('#' + sId + '').val();
        sDate = sDate.replace(/^\s+|\s+$/g, '') ;
    var patt = new RegExp(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i);
        return patt.test(sDate);

}

function countChars(iId, iMax)
{
   if(document.getElementById(iId).value.length<=iMax)
  {
      a=document.getElementById(iId).value.length;
      c=iMax-a;
      document.getElementById('counter_' + iId + '').innerHTML = c;
   }
   else
   {
      document.getElementById(iId).value = document.getElementById(iId).value.substr(0, iMax);
   }
}


function stripTags(sText){
    return sText.replace(/<\/?[^>]+>/gi, '');
}
function cutString(sText, stop){
    return sText.substring(0, stop) 
}

function newsLetterAction(){

    var sMail = jQuery('#newsletterField_').val();
    var bError = false;
   
    if(!echeck(sMail)){
        bError = true;
        jQuery("#newsletterField_").addClass('error');
        jQuery("#newsLetter_info").html('Wpisany adres E-mail jest nieprawidłowy.');
        //jQuery("#newsLetter_info").show();
        jQuery("#newsLetter_info").addClass('info-error');
     } else {
        jQuery("#newsletterField_").removeClass('error');
     } 
     
     if(!bError){
        jQuery("#newsLetter_info").html('Trwa wprowadzanie zmian. Proszę czekać...');
        jQuery("#newsLetter_ele_link").hide();
        jQuery("#newsLetter_ind").show();
        jQuery("#newsLetter_info").removeClass('info-error');
        
        jQuery.post(getFileName() + "/commons/actionmail", { mail: "" +  sMail + ""}, function(data){
                    jQuery("#newsLetter_info").html(data);
                    jQuery("#newsLetter_ind").hide();
                    jQuery("#newsLetter_ele_link").show();
                    
            });
        
     }
}

function checkIsBackAllowed(){

    var iTimes = parseInt(history.length);
    //alert(iTimes);
    if(iTimes > 0){
       jQuery('#back_referer_path').show(); 
    }
}

function returnPreviesPage(){
    
    history.go(-1);
}


function changeSwitcher(iIds, iCountInteresting, bResetTime){
    
    //get iCurrentSwitch global
        
    if(iCurrentSwitch != iIds){
    iCurrentSwitch = iIds;
    jQuery('#switcher_loader').show();
    
    //set timer again to 0
    if(bResetTime != undefined){
      clearTimeout(oTimer); 
      switchNextInterval(iCountInteresting)
    }
    
    for(var i = 0; i < iCountInteresting; i++){
        
        if(i == iIds){

            var oDiv = document.getElementById('switcher_box' + iIds);
            var oLink = document.getElementById('swither_link_id' + iIds);

            oLink.className =  'inactive'
            oDiv.className = 'active holder'; 
            oDiv.blur();
            
            oLink.onmouseover = function(){
             };
             
            oLink .onmouseout = function(){
               this.style.textDecoration = 'none';
             };
             
            oDiv.onmouseover = function(){
             };
             
            oDiv.onmouseout = function(){
            this.style.textDecoration = 'none';
             };
             
            oLink.style.textDecoration = 'none';
            
            
        }else {
          try{//sometimes error accour
            
            var oDiv = document.getElementById('switcher_box' + i);
            var oLink = document.getElementById('swither_link_id' + i);
            
            oLink.className = ''; 

            oDiv.className = 'holder';
            
            oLink.onmouseover = function(){
             this.style.textDecoration = 'underline';
             };
             
            oLink .onmouseout = function(){
             this.style.textDecoration = 'none';
             };
             
            oDiv.onmouseover = function(){
             this.style.textDecoration = 'underline';
             };
             
            oDiv.onmouseout = function(){
             this.style.textDecoration = 'none';
             };
          
            
            oLink.style.textDecoration = 'none';

            oDiv.className = 'holder'; 
            oDiv.blur();
            
           }catch(err){}
        }
        
    }
    
    //change bacground image 
    _switchSmallImage(iCountInteresting, iIds);
    
   loadNextInterestingOffer(iIds); 
   }    
}

function _switchSmallImage(iCountInteresting, j){

	//alert(j);
	for(var i = 0; i < iCountInteresting; i++){
	   
	    var oImage = document.getElementById('image_load_holder_img_small_' + i);
	    //alert(oImage.src.indexOf('34x22gray'));
       if(oImage && oImage.src.indexOf('34x22_no_photo') < 0){
		    if(j == i){
				if(oImage.src.indexOf('34x22gray') > 0){
				   oImage.src = oImage.src.replace('34x22gray', '34x22');
				}
			} else {
				if(oImage.src.indexOf('34x22gray') < 0){
				   oImage.src = oImage.src.replace('34x22', '34x22gray');
				} 
			}
		}
	}
	
}

function _generateStars(iNumber, sDestination){
        
          var sPath = '';  
          
          if(iNumber > 1){
              var iStars  = parseInt((iNumber/ 10));
              for(var i = 0; i < iStars; i++){
              sPath +='<img src="/images/' + sCatalogSysView + '/icons/star.gif" class="star">';
              }
              if((iNumber)%10){ 
               sPath +='<img src="/images/' + sCatalogSysView + '/icons/star-half.gif" class="star-half.gif">';
              }
          }
          
          jQuery('#' + sDestination).html(sPath);
}

function switchNextInterval(iCountInteresting){
    
       oTimer = setTimeout(function () {
        
            var iNext = iCurrentSwitch+1;
            
            if((iNext) >= iCountInteresting){  
                iNext = 0;
            } 

            changeSwitcher(iNext, iCountInteresting);
            iCurrentSwitch = iNext; 
            
            switchNextInterval(iCountInteresting);
        }, iTimeout);

}

function redirectToReservation(sPath){

    window.location.href= sPath;
}

function changeImageButtonElement(sId, sClass, sText1, sClassSnd, sText2){ 
        
        if(jQuery('' + sId + '').hasClass('' + sClass + '')){
           //alert(jQuery('' + sId + '').width()); 
           jQuery('' + sId + '').removeClass('' + sClass + '').addClass('' + sClassSnd + '').find('' + sId + '_content').html(sText2); 
        } else {
           jQuery('' + sId + '').removeClass('' + sClassSnd + '').addClass('' + sClass + '').find('' + sId + '_content').html(sText1); 
        }
}

function classSwitchChange(sId, sClass){
        if(jQuery('' + sId + '').hasClass('' + sClass + '')){
           jQuery('' + sId + '').removeClass('' + sClass + '');
        } else {
            jQuery('' + sId + '').addClass('' + sClass + '')
        }
}

function stripTags(sText){
    return sText.replace(/<\/?[^>]+>/gi, '');
}

function getCurrencyFormat(sValue, sCurrencyAcronym, sCurrencyCulture){
    
    if(sCurrencyAcronym == 'PLN' && sCurrencyCulture == 'pl_PL'){
        return sValue + ' zł'; 
      } else if(sCurrencyAcronym == 'EUR' && sCurrencyCulture == 'en_US'){
        return  '€' + sValue; 
      } else if(sCurrencyAcronym == 'HUF' && sCurrencyCulture == 'hu_HU'){
    	  return  '' + sValue + ' Ft'; 
      } else if(sCurrencyAcronym == 'ROL' && sCurrencyCulture == 'ro_RO'){
    	  return  '' + sValue + ' lei'; 
      } else if(sCurrencyAcronym == 'CZK' && sCurrencyCulture == 'cs_CZ'){
    	  return  '' + sValue + ' Kč'; 
      } else if(sCurrencyAcronym == 'GBP' && sCurrencyCulture == 'en_GB'){
        return  '£' + sValue; 
      } else {
        return sValue;
      }
}

function copyPasteInputs(s1, s2){
    jQuery('#' + s2).val(jQuery('#' + s1).val());
}

function checkNip(nip){
	
	var weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
	nip = nip.replace(/[\s-]/g, '');
	 
    if (nip.length == 10 && parseInt(nip, 10) > 0) {
            var sum = 0;
            for(var i = 0; i < 9; i++){
                    sum += nip[i] * weights[i];
            }                     
            return (sum % 11) == nip[9];
    }
    return false;                
}

function checkPesel(pesel){

    var aPesel = new Array();    
    var iSuma = 0;
    var aWagi = new Array(1, 3, 7, 9, 1, 3, 7, 9, 1, 3);
    
    if(pesel.length == 11){   
     
        for(i = 0; i < (pesel.length); i++){
            aPesel[i] = pesel.substr(i,1);
        }
        //alert(aPesel.length)
        
        var iControlNumber = aPesel[aPesel.length - 1];
        
        for(i = 0; i < (aPesel.length -1); i++){
            iSuma+= (aPesel[i]*aWagi[i]);
        }   
        
        //iSuma += aPesel[aPesel.length-1];
        
        var iReszta = (10 - (iSuma%10)) % 10;
            //iReszta = 10 - iReszta;
            //alert(iReszta);
            return (iControlNumber == iReszta);   
        
    } else {
        return false;
    }   
}

function countDays(sDay1, sDay2){
   
   var iDays1 = 0;
       
   while(sDay1.getTime() != sDay2.getTime()){
        iDays1++;
        sDay1.setDate(sDay1.getDate() + 1); 
   }
   return iDays1; 
}

function addOverlayToObject(sId){
       
       if($('#' + sId + '').length > 0){
          return false;
       } 
        
       $('body').append('<div id="' + sId + '"></div>');
	   $('#' + sId + '')
		.css('opacity','0.4')
		.css('position','fixed')
		.css('background-color','#0A5B9D')
		.css('z-index','2000')
		.css('height',$(window).height() + 'px')
		.css('width',$(window).width() + 'px')
		.css('top','0')
		.css('left','0').html('<div id="' + sId + '_loader"><img src="/images/frontend/loaders/cursor_big.gif" /></div>');
		$('#' + sId + '_loader')
		.css('position','fixed')
		.css('color','#000')
		.css('z-index','2001')
		.css('height','300px')
		.css('width','300px')
		.css('top','50%')
		.css('left','50%');
}
function deleteOverlayFromObject(sId){

       $('#' + sId + '').remove();
}
function selectAllInSelect(sId){
       $('#' + sId + ' option').attr('selected', 'selected');
}


Array.prototype.getMax = function()
{
var max = Number.MIN_VALUE, v, len = this.length, i = 0;
if(len < 1){
  return 0;
}
for (; i < len; ++i){
    if (typeof (v = this[i]) == 'number'){
        max = Math.max(max, v);
    }
}
return max;
}

Array.prototype.getMin = function()
{
var min = Number.MAX_VALUE, v, len = this.length, i = 0;
if(len < 1){
  return 0;
}
for (; i < len; ++i)
if (typeof (v = this[i]) == 'number')
min = Math.min(min, v);
return min;
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}


