//Global variable to decide whether loading image needs to display or not on AJAX request.
var _isShowLoading = true;

function BeginRequestHandler(sender, args)
{    
    //Check _isShowLoading variable value.
    if(document.getElementById('divLoading').style.display=="none" && _isShowLoading == true)
    {   
        DisplayInCenter('divLoading','');
        ShowControl('divModalBack');
    }
}

function EndRequestHandler(sender, args)
{
    document.title = document.title.replace(/&amp;/g,'&');
    HideControl('divLoading');
    HideControl('divModalBack');
    //Reset variable.
    _isShowLoading = true;
}

function ShowControl(cnt)
{
    tCnt = document.getElementById(cnt);
    if(tCnt.style.display == 'none')
        tCnt.style.display ='';     
        return true;
}

function HideControl(cnt)
{
    var tCnt = document.getElementById(cnt);
    if(tCnt != null && tCnt != "undefined" )
    {
        if(tCnt.style.display == 'block')
            tCnt.style.display ='none';
        else if(tCnt.style.display == '')
            tCnt.style.display ='none';
            return true;    
    }
    
}

function getScrollTop()
{
	return this.pageYOffset || document.documentElement.scrollTop;
}

function DisplayInCenter(ElementId,hidElementId)
{
    var hDiv = document.getElementById(hidElementId);
    if (hDiv != null && hDiv != 'undefined')
    {
        document.getElementById(hidElementId).style.display = 'none';
    }
    
    var oDiv = document.getElementById(ElementId);    
    if (oDiv != null && oDiv != 'undefined')
    {
        var oBody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;		
        document.getElementById(ElementId).style.display = "block";
     
        var DivWidth = parseInt(document.getElementById(ElementId).offsetWidth,10);
        var DivHeight = parseInt(document.getElementById(ElementId).offsetHeight,10);

        //document.getElementById(ElementId).style.left = ((document.body.offsetWidth / 2) - (DivWidth / 2)) + "px";
        document.getElementById(ElementId).style.left = ((oBody.clientWidth/2) - (DivWidth / 2)) + "px";
        //document.getElementById(ElementId).style.top =  ( oBody.scrollTop + (document.body.offsetHeight / 2) - ( DivHeight / 2) - 100) + "px";
        document.getElementById(ElementId).style.top =   ( (getScrollTop() +(document.documentElement.clientHeight/2))  - ( DivHeight / 2)) + "px";
   }
}

/////////////////////////////////////////////////////////////
//Client side error handling function starts from here.
/////////////////////////////////////////////////////////////
function __ErrorHandler()
{
	this.prefix = "";
	this.header = "";

	oDiv = document.getElementById("divError");
	if(oDiv == "undefined")
	{
		alert("'divError' not defined on this page.");
	}
}
__ErrorHandler.prototype = 
{
	isBlank: function()
	{
		return oDiv.innerHTML == "";
	},
	showError: function()
	{
		if(this.isBlank() != true)
		{
			oDiv.style.display = "block";
		}
	},
	hideError: function()
	{
		oDiv.style.display = "none";
	},
	clearError: function()
	{
		oDiv.innerHTML = "";
		this.hideError();
	},
	addError: function(str)
	{
	  var strHTML = "";

	  if(this.isBlank())
	  {
		strHTML += this.header;
		strHTML += "</p>";
	  }
	  else
	  {
      	strHTML += "<br>";
	  }

	  strHTML += this.prefix + ' ' + str;
	  oDiv.innerHTML += strHTML;
	}
}

function fnDo(str)
{
	var oName = document.getElementById("txtName");
	var oErr = new __ErrorHandler();
	
	oErr.prefix = "-";
	switch (str)
	{
		case 'add':
			{
				oErr.addError('An Error was added');
			}
		case 'show':
			{
				oErr.showError();
				break
			}
		case 'clear':
			{
				oErr.clearError()
				break;
			}
		case 'hide':
			{
				oErr.hideError()
				break;
			}
		default:
			break;
	}
	document.getElementById("txtdebug").innerText =  document.getElementById("divError").innerHTML;

}
/////////////////////////////////////////////////////////
//End
////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////
//Used to check whether the email address is in correct format or not.
//////////////////////////////////////////////////////////////////////
function CheckMailAddressFormat( sEmailAddress )
{
    //Check whether the specified email address is in correct format or not.
    var sEmail = new String( sEmailAddress );
    var emailValid = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9_\.\-])+\.)+([a-zA-Z0-9]{2,4})$/;

    if( emailValid.test( sEmail ) == false)
    {
        return false;
    }
    
    return true;
}

/////////////////////////////////////////////////////////
//Used to trim the string.
////////////////////////////////////////////////////////
function Trim(tstrInput)
{
	return (tstrInput.replace(/^ *| *$/g,""));
}

///////////////////////////////////////////////////////
//Used this function to allow only characters.
////////////////////////////////////////////////////////
function fnAllowOnlyCharacters( eObj )
{
    var oKey;
    
	if( navigator.userAgent.toLowerCase().indexOf("msie") != -1 )
	{ 
		oKey = eObj.keyCode;
	}
	else if( navigator.product == "Gecko" )
	{
		oKey = eObj.which;
	}
		
	if( ( oKey > 47) && ( oKey < 58) )
	{
		return false;
	}
	return true;
}

////////////////////////////////////////////////////////
//Used this function to allow only numeric values.
////////////////////////////////////////////////////////
function fnAllowOnlyNumerics( eObj )
{
    var oKey;
    
	if( navigator.userAgent.toLowerCase().indexOf("msie") != -1 )
	{ 
		oKey = eObj.keyCode;
	}
	else if( navigator.product == "Gecko" )
	{
		oKey = eObj.which;
	}
		
	if( (( oKey > 47) && ( oKey < 58)) || oKey == 8 || oKey == 0 )
	{
		return true;
	}
	return false;
}


/////////////////////////////////////////////////////////////////////////////////
//Used to allow custom characters. Pass all the custom chars in seconde parameter.
//Example if you want to allow '(' and ')' then call this function as 
//                  fnAllowCustomChars( event , '('')' )
/////////////////////////////////////////////////////////////////////////////////

function fnAllowCustomChars( eObj , sChars )
{
    var oKey;
    
	if( navigator.userAgent.toLowerCase().indexOf("msie") != -1 )
	{ 
		oKey = eObj.keyCode;
	}
	else if( navigator.product == "Gecko" )
	{
		oKey = eObj.which;
	}
    
    
	if( ( oKey > 64 && oKey < 91 ) || ( oKey > 96 && oKey <123 ) || ( oKey > 47 && oKey < 58 ) || oKey == 8 || oKey == 0 )
	{
		return true;
	}
	else 
	{
	    var sAllowChars = new String( sChars );  
	    var cChar       = "'" + String.fromCharCode( oKey ) + "'";
	    
	    if( sAllowChars.indexOf( cChar ) != -1 )
	    {
	        return true;
	    }
	}
	return false;
}

// Given by abhishek soni from tempo project
// Starts
//////////////////////////////////////////////////////////////////
//Trim the editor content.
/////////////////////////////////////////////////////////////////
function TrimEditor( strValue )
{

    var sValue = new String(strValue);
    sValue = sValue.replace( /&nbsp;/g, "");
    sValue = sValue.replace( /<p>/g, "");
    sValue = sValue.replace( /<\/p>/g, "");
    sValue = sValue.replace( /<P>/g, "");
    sValue = sValue.replace( /<\/P>/g, "");
    sValue = sValue.replace( /<br>/g, "");
    sValue = sValue.replace( /<BR>/g, "");
    
//    if ( sValue.indexOf("<p>") == 0 )
//        sValue = sValue.substring( 3 );
//    if( sValue.lastIndexOf("</p>") == sValue.length - 4 )
//        sValue = sValue.substring( 0 ,  sValue.lastIndexOf("</p>") );
//    if( sValue.lastIndexOf("<br>") == sValue.length - 4 )
//        sValue = sValue.substring( 0 ,  sValue.lastIndexOf("<br>") );
    
    return sValue;
}


function TextEditorValidator(objifr,ErrorMessage)
{
    //alert("TextEditorINN");
    ifr = objifr;
    if (ifr)
    {
        var ifrDoc = ifr.contentWindow ? ifr.contentWindow.document : ifr.contentDocument;
        var edittd = ifrDoc.getElementById("xEditingArea");
        
        if( edittd.childNodes[0].tagName == "IFRAME")
        {
            ifr = ifrDoc.documentElement.getElementsByTagName("IFRAME")[0] ;
            ifrDoc = ifr.contentWindow ? ifr.contentWindow.document : ifr.contentDocument;
            
            var ifrbdy = ifrDoc.documentElement.getElementsByTagName('body').item(0);
            if (ifrbdy) 
            { 
              if( Trim( TrimEditor( ifrbdy.innerHTML ) ) == "" )
              {
                  //ErrorObj.addError(ErrorMessage);
                  //ErrorObj.showError();
                  return false;
              }
            }
        }
        else
        {
            if( Trim( TrimEditor( edittd.childNodes[0].value ) )  == "" )
            {
                //ErrorObj.addError(ErrorMessage);
                //ErrorObj.showError();
                return false;
            }
        }
    }
}
     

function fnValidateDate(stringFormat)
{
    var str = stringFormat.split("/")
    if(str.length == 0)
    {
        return false;
    }
    else
    {
        if(str.length != 3)
        {
            return false;
        }
        else
        {
            try
            {
                
                if(isNaN(str[0]) || isNaN(str[1]) || isNaN(str[2]))
                {
                    return false
                }
                //alert("dd");
                if(str[1] == "08")
                {
                    m = 8;
                }
                else if(str[1] == "09")
                {
                    m = 9;
                }
                else
                {
                    m = parseInt(str[1]);
                }
                if(str[0] == "08")
                {
                    d = 8;
                }
                else if(str[0] == "09")
                {
                    d = 9;
                }
                else
                {
                    d = parseInt(str[0]);
                }
                
                y = parseInt(str[2]);
                if(str[2].length != 4)
                {
                    return false;
                }
                monthValid = false;
                
                if(m >=1 && m <=12)
                {
                    monthValid = true;
                }

                dayValid = false;
                
                if( (m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) && ( d >= 1 && d <= 31 ) )
                {
                    dayValid=true;
                }
                else if( (m==4 || m==6 || m==9 || m==11 ) && ( d >= 1 && d <= 30 ) )
                {
                    dayValid=true;
                }
                else if( m == 2 && ( d >= 1 && d <= 29 ) )
                {
                   // dayValid=true;
                   //alert(d);
                   if(d == 29)
                   {
                        if(y%4==0 && y%100 != 0)
                        {
                            dayValid=true;
                        }
                        else
                        {
                            if(y%400 == 0)
                            {
                                dayValid=true;
                            }
                        }
                    }
                    else
                    {   
                        if( m == 2 && ( d >= 1 && d <= 28 ) )
                        {
                            dayValid=true;
                        }
                    }
                    
                }
                
                if(monthValid == false || dayValid == false)
                {
                    return false;
                }
                return true;
             }
             catch(ex)
             {
                return false;
             }
        }
    }
}




function TextEditorValidator(objifr,ErrorMessage)
{
    //alert("TextEditorINN");
    ifr = objifr;
    if (ifr)
    {
        var ifrDoc = ifr.contentWindow ? ifr.contentWindow.document : ifr.contentDocument;
        var edittd = ifrDoc.getElementById("xEditingArea");
        
        if( edittd.childNodes[0].tagName == "IFRAME")
        {
            ifr = ifrDoc.documentElement.getElementsByTagName("IFRAME")[0] ;
            ifrDoc = ifr.contentWindow ? ifr.contentWindow.document : ifr.contentDocument;
            
            var ifrbdy = ifrDoc.documentElement.getElementsByTagName('body').item(0);
            if (ifrbdy) 
            { 
              if( Trim( TrimEditor( ifrbdy.innerHTML ) ) == "" )
              {
                  //ErrorObj.addError(ErrorMessage);
                  //ErrorObj.showError();
                  return false;
              }
            }
        }
        else
        {
            if( Trim( TrimEditor( edittd.childNodes[0].value ) )  == "" )
            {
                //ErrorObj.addError(ErrorMessage);
                //ErrorObj.showError();
                return false;
            }
        }
    }
}

// Ends
/* Moved here from AgentTestimonials.js */
function fnAllowOnlydate( eObj )
{
    var oKey;
    
	if( navigator.userAgent.toLowerCase().indexOf("msie") != -1 )
	{ 
		oKey = eObj.keyCode;
	}
	else if( navigator.product == "Gecko" )
	{
		oKey = eObj.which;
	}
	if( ((oKey == 38)||(oKey == 45)||( oKey >= 47) && ( oKey < 58)) || oKey == 8 || oKey == 0 )
	{
		return true;
	}
	else
	{
    	return false;
    }
}

function SetPage(pagename, cmsPage)
	{
		  
		if(document.getElementById('beIframe') != null)
		{
		  var iFrame = document.getElementById('beIframe');
		  if(pagename.indexOf('Logout.aspx',0))
		  {
			var menuIframe = document.getElementById('menuIframe');
			menuIframe.src = menuIframe.src ;
		  } 
		  iFrame.src=pagename;
		  }
		  else
		  {
			   var browUrl = window.location.href;
			   browUrl = browUrl.toLowerCase();
			   var siteUrl = '';

			   if(browUrl.indexOf('home.aspx') >= 0)
			   {
					siteUrl = "/CMS/Home.aspx?setBEPage=" + pagename;
					
					if( typeof(cmsPage) != 'undefined')
					    siteUrl +=  "&cmspage=" + cmsPage ;
			   }
			   else
			   {
					siteUrl = "/CMS/BookingGateway.aspx?setBEPage=" + pagename;
					
					if( typeof(cmsPage) != 'undefined')
					    siteUrl +=  "&cmspage=" + pagename;
			   }

			   window.location = siteUrl;
		  }
	}
/* Modified on 21/12/2009 - Co-ordinate with Jaydeep Parekh to adde new param "pagename" which would contain the page name to set into iframe */
function SetLoginStatus(loginstatus,usertype,pagename,cmsPage)
{
    var pID = document.getElementById('hdPortalId').value;
    var pAlias = document.getElementById('hdPortalAlias').value;
    
	jQuery.ajax({type: "POST", url: "/cms/integration/gateway.aspx",data: "LoginStatus="+loginstatus+"&UserType="+usertype+"&hdPortalAlias="+pAlias+"&hdPortalId="+pID,
    success: function(msg)
			{			    
				var siteUrl = '';

			    var strStatus = new String(loginstatus);
			    if( strStatus.toLowerCase() == "logoff")
			    {
			        siteUrl = "/CMS/home.aspx";
			    }
				else
				{
					var bookingIframe = document.getElementById('beIframe');
					if(bookingIframe != null) {

						var browUrl = bookingIframe.src;
						browUrl = browUrl.toLowerCase();

                        //Commenting BookingGateway.aspx siteurl and updating it with Home.aspx as per talk with Alok on 10-May-10
                        //This if-else condition will be removed as now we have to set Home.aspx page, but we will remove it once testing is done
						if(browUrl.indexOf('loginmaster.aspx') >= 0)
						{
							//siteUrl = "/CMS/BookingGateway.aspx";
							siteUrl = "/CMS/Home.aspx";
						}
						else											
							siteUrl = "/CMS/Home.aspx";

					} else {
							siteUrl = "/CMS/Home.aspx";
					}
					
					if( typeof(cmsPage) != 'undefined')
					{
					    siteUrl = "/CMS/" + cmsPage;
					}
				}

				siteUrl += ((typeof pagename != 'undefined' && pagename != null && pagename != '')  ? "?setBEPage=" + pagename : '');
				
				window.location = siteUrl;
            }    
	    }
	);
}

/*Added by Ruchir Patel on 17-06-2010.*/
function fnGetOffsetTop (oEl)
{
	var iTop = oEl.offsetTop;
	while((oEl = oEl.offsetParent) != null)
	{	iTop += oEl.offsetTop;		}
       // alert("Parent: " + iTop)
	return iTop;
}

function fnGetOffsetLeft (oEl)
{
	var iLeft = oEl.offsetLeft;
	while ((oEl = oEl.offsetParent) != null)
		{	iLeft += oEl.offsetLeft;		}
       // alert("Parent: " + iTop)
	return iLeft;
}

/* Login/Logout user in CMS and redirect user to the appropriate page. */
function WidgetSetLoginStatus(loginstatus,usertype,pagename,cmsPage)
{
    var pID = document.getElementById('hdPortalId').value;
    var pAlias = document.getElementById('hdPortalAlias').value;
    
	jQuery.ajax({type: "POST", url: "/cms/integration/gateway.aspx",data: "LoginStatus="+loginstatus+"&UserType="+usertype+"&hdPortalAlias="+pAlias+"&hdPortalId="+pID,
    success: function(msg)
			{
				if(pagename == '' || typeof(pagename) == 'undefined')
	            {
		            window.location = "/CMS/Home.aspx";
	            }
	            else
	            {	
		            window.location = pagename;
	            }
            }    
	    }
	);	
}

/* To Display Agent/Customer sign up box in CMS. */
function WidgetDisplayLogin(widgetName)
{
    var pBEURL = document.getElementById('hdBEURL').value;
    if( pBEURL != "" )
    {
        window.location = pBEURL + "?widgetName=" + widgetName;
    }
}

//Moved from ASCX to here for the common use
//Problem was after searching from BE the inner page is not
//returning Agency menu and no JS page load function called to reset
//AgencyLogin link
function SetAgencyMenuPosition()
{
    var objMenu = document.getElementById("BEMenu");
    if(objMenu != null)
    {
        var objCMSMenuDiv = document.getElementById('dvAMenu');
        objMenu.style.left =  fnGetOffsetLeft(objCMSMenuDiv) + 'px';
        objMenu.style.top = fnGetOffsetTop(objCMSMenuDiv) + 'px';
        objMenu.style.width = objCMSMenuDiv.offsetWidth + 'px';
    }
}

//Added by Ruchir on 5-Aug. To display message on language change.
function fnLanguageClick(sURL , objSelect, sCurValue)
{
    if(confirm("You have selected to view this site in " + objSelect.options[objSelect.selectedIndex].text + ". You will now be redirected to the home page."))
    {
        window.location = sURL + "?language=" + objSelect.value;
        return false;
    }
    else
    {
        objSelect.value = sCurValue;
    }
    return false;
}


function BusinessChanged(sender, newBusiness)
{
    //Set variable value to false so AJAX loading image will not be displayed.
    _isShowLoading = false;
    sender = sender.toUpperCase();
    newBusiness = newBusiness.toUpperCase();
    if(sender == "BE")
    {
        var eleID = GetCMSElementIDByBusiness(newBusiness);
        //alert(jQuery("#" + eleID).attr('href') + ' --- ' + eleID);
        //jQuery("#" + eleID).click();
        var hREF = jQuery("#" + eleID).attr('href');
        eval(hREF);
    }
    else if(sender == "CMS")
    {
        var strBEBusiness = "";
        switch (newBusiness.toLowerCase())
	        {
	             case 'hotels':
			        {
				        strBEBusiness = 'Hotel';break;
			        }
		        case 'flights':
			        {
				        strBEBusiness = 'Air';break;
			        }
		        case 'restaurant':
			        {
				        strBEBusiness = 'Restaurant';break;
			        }
		        case 'cars':
			        {
				        strBEBusiness = 'Vehicle';break;
			        }
			   case 'activities':
			        {
				        strBEBusiness = 'Activity';break;
			        }
		        case 'bus':
			        {
				        strBEBusiness = 'Bus';break;
			        }
		        default:
			        break;
	        }
	        if(strBEBusiness != "")
	            { ChangeWidget(strBEBusiness);}
    }
}

function GetCMSElementIDByBusiness(newBusiness)
{
    for(i=0;i<=CMSProducts.length-1;i++)
    {
        var sVal = CMSProducts[i].split("~");
        if(sVal[0].toUpperCase() == newBusiness.toUpperCase())
        {
            return sVal[1];
        }
    }
    return "";
}
