// JScript File
//JNA011008: Generic confirmation popup with popup message as parameter.
function ConfirmAction(message)
{
if(confirm(message)==true)
    return true;
   else
    return false;
}

//JNA012308: Function to calculate the total number of seats in the EventCreate page.
function CalculateTotalSeats(rows, seats, lblId)
{
    var row = aspxGetControlCollection().Get(rows);
    var seat = aspxGetControlCollection().Get(seats);
    
    row = row.GetValue();
    seat = seat.GetValue();  


    var totalseats = 0;
    if(IsNumeric(row) && IsNumeric(seat))
    {
        totalseats = row * seat;    
    }
    document.getElementById(lblId).value = totalseats;
}

//JNA012308: Function to determine whether a value is numeric or not.
function IsNumeric(value)
{
    var regex = /^\d+$/;
    if(!regex.test(value))
    {
        return false;
    }
    else
    {
        return true;
    }
}

function MaxLength(clientId, maxLength)
{
    //alert('Testing]' + clientId + '[');
    var testValue = aspxGetControlCollection().Get(clientId);
    //alert(testValue.GetValue());
    
    var testValueLength = testValue.GetText();
    //alert(testValueLength.length);
    
    if (testValueLength.length > maxLength)
    {
        var cutValue = testValueLength.substring(0, maxLength);
        testValue.SetValue(cutValue);
        //alert(cutValue);
    }
         
}

function MaxLengthWC(clientId, maxLength)
{
    //alert('Testing]' + clientId + '[');
    var testValue = aspxGetControlCollection().Get(clientId + "_I");
    alert(testValue.GetValue());
    
    var testValueLength = testValue.GetText();
    //alert(testValueLength.length);
    
    if (testValueLength.length > maxLength)
    {
        var cutValue = testValueLength.substring(0, maxLength);
        testValue.SetValue(cutValue);
        //alert(cutValue);
    }
         
}
function SetMaxLength(clientId)
{
    alert('Hello!');
    document.getElementById(clientId).maxLength = 10;
}

//RFR012308: Function to call when UpdatePanel is updating
 function onUpdating(wizardClientId, updateProgressDivId){
 
        // get the update progress div
        var updateProgressDiv = $get(updateProgressDivId); 
        // make it visible
        updateProgressDiv.style.display = '';

        //  get the wizard element        
        var wizard = $get(wizardClientId);
         
        
        // get the bounds of both the wizard and the progress div
        var wizardBounds = Sys.UI.DomElement.getBounds(wizard);
        var updateProgressDivBounds = Sys.UI.DomElement.getBounds(updateProgressDiv);
        
        //	do the math to figure out where to position the element (the center of the gridview)
        var x = wizardBounds.x + Math.round(wizardBounds.width / 2) - Math.round(updateProgressDivBounds.width / 2);
        var y = wizardBounds.y + Math.round(wizardBounds.height / 2) - Math.round(updateProgressDivBounds.height / 2);
        
        //	set the progress element to this position
        Sys.UI.DomElement.setLocation (updateProgressDiv, x, y);        
    }

//RFR012308: Function to call when UpdatePanel has finished updating 
function onUpdated(updateProgressDivId) {
    // get the update progress div
    var updateProgressDiv = $get(updateProgressDivId); 
    // make it invisible
    updateProgressDiv.style.display = 'none';
}

//RFR04022008: opens a new window in modal mode
function fn_openModal(url,parent,h,w){	
	if(window.showModalDialog)
		showModalDialog(url,parent,'dialogHeight:'+h+'px;dialogWidth:'+w+'px;scroll:yes;help:no;status:no;menubar:yes;');		
	else{
		var left = Math.round((screen.availWidth-w)/2);
		var top = Math.round((screen.availHeight-h)/2);
		w = Math.round(w * .99);
		h = Math.round(h * .85);
		window.open(url,'','status=no,toolbar=no,menubar=yes,scrollbars=yes,location=no,resizable=1,modal=yes,height='+h+',width='+w+',left='+left+',top='+top);
	}				
}

function ValidateEmail(strEmail){
//var isValid = false;
var input_str=strEmail;
var input_len1=input_str.length;
var iserror=0;

    input_len1=input_str.length;

    if (input_len1 <= 5) {
        //alert("You must enter a Valid Email Address!\n");
        iserror=1;
    }

    var lastdot=-1;
    var lastat=-1;
    var numberat=0
    for (var j = 0; j < input_len1; j++) {
         var ch2 = input_str.substring(j, j + 1);
         if (((ch2 < "a") ||  (ch2 > "z")) && ((ch2 < "A") || (ch2 > "Z")) && ((ch2 < "0") ||  (ch2 > "9")) && (ch2 != "@" ) && (ch2 != ".") && (ch2 != "_") && (ch2 != "-")){
             //alert("Please input a valid email address!\nValid characters include A-Z, a-z, 0-9, -, _, . and @");
             iserror=1;
         }
         if (ch2==".") {
             if ( j == lastdot + 1) {
                 //alert("Please input a valid email address!\nYou can't have two dots next to\neach other'..'.");
                 iserror=1;
             }
             lastdot=j;
         }
         if (ch2=="@") {
             lastat=j;
             numberat=numberat+1
         }
         if (ch2==" ") {
             //alert("Please input a valid email address!\nYou can't have any spaces in the address.");
             iserror=1;
         }
    }
    if (lastat == -1) {
         //alert("Please input a valid email address!\nYou don't have an '@'.");
         iserror=1;
    }
    if (lastat == 0) {
         //alert("Please input a valid email address!\nYou don't have a name before the '@'.");
         iserror=1;
    }
    if (numberat > 1) {
         //alert("Please input a valid email address!\nYou may have only one '@'.");
         iserror=1;
    }
    if ((lastdot <= lastat) || (lastdot > input_len1 - 3 ) || (input_len1 - lastdot > 10)) {
         //alert("Please input a valid email address!\nYou don't have a proper domain name!\nUse .com, .org, .net, .cc, etc");
         iserror=1;
    }
    if (lastdot == lastat + 1) {
         //alert("Please input a valid email address!\nYou don't have a proper organization name!\nUse name@organization.domain");
         iserror=1;
    }
    if (iserror==1) {
         return false;
    }
    else
	   return true;
}

//JRMT05202008: Function to redirect search
function RedirectSearch(urlRedirect)
{
    var qstring = document.getElementById('txtSearch').value;
    location.href = urlRedirect + '?keyword=' + qstring;
}

    
  //RFR062508: Function to redirect to search when pressing enter key
  function GoSearch (e, urlRedirect) {
        //user press an enter key
        
        var keynum;
        
        //if IE
        if (window.event) 
        {
            keynum = e.keyCode;
            if (keynum == 13) {
                RedirectSearch(urlRedirect);
             }
            
        }
        //if  Netscape/Firefox/Opera
        else if (e.which) 
        {
            keynum = e.which;

            if (keynum == 13) {
                RedirectSearch(urlRedirect);
            }
        
        }
         
         return true;   
            
    }

//JNA062608: Function to redirect to login when pressing enter key
function GoLogin (e)
{
    var keynum;
        
        //if IE
        if (window.event) 
        {
            keynum = e.keyCode;
            if (keynum == 13) {
                document.frmLogin.submit();
             }
            
        }
        //if  Netscape/Firefox/Opera
        else if (e.which) 
        {
            keynum = e.which;

            if (keynum == 13) {
                document.frmLogin.submit();
            }
        
        }
         
         return true;   
}

//AAD022309: Function to check if string is a potentially dangerous script or html
function ValidateString(controlId)
{
    var control = aspxGetControlCollection().Get(controlId);
    var strVal = "";
    if(control.GetValue() == null)
    {
        strVal = "";
    }
    else
    {
        strVal =  control.GetValue();
    }
    
    var regX = /<(\S*).*(>)?(.*)(<\/\1>)?/;
    //MJGE04192011: Issue 22743 - should not accept '< >' with spaces between
	//var regX = /<(\S+).*(>)?(.*)(<\/\1>)?/;
	//checks if string is a script or html
	//var strMatch = strVal.match(regX);
	//if(strMatch == null || strMatch == '')
	if(!regX.exec(strVal))
	{
        return true;
    }
    else
    {
        return false;
    }  
}

//MJGE051611: Function to validate decimal from control's value
//controlId = Id of Control to be validate
//options = options to include in validation:
//              - IsNullAllowed: Allow Null Values
//              - MinimumNumber: Minimum Allowed Value
function ValidateDecimal(controlId, options)
{
    var control = aspxGetControlCollection().Get(controlId);
    var returnObject = { IsValid : true, ErrorText : '' };
    var stringValue = '';
    
    //Initialize variables from options argument
    var isNullAllowed = (options == null) ? false : (('IsNullAllowed' in options) ? options.IsNullAllowed : false );
    var minimumNumber = (options == null) ? false : (('MinimumNumber' in options) ? options.MinimumNumber : false );
    
    //Check if value is null
    if (control.GetValue() == null)
    {
        returnObject.IsValid = isNullAllowed;
        returnObject.ErrorText = 'Invalid Value';
    }
    else
    {
        var decimalValue = 0.00;
        var decimalIndex = 0;
        
        stringValue = control.GetValue();
        
        //Check if value is decimal
        if (!IsDecimal(stringValue))
        {
            returnObject.IsValid = false;
            returnObject.ErrorText = 'Invalid Value';
        }
        else
        {
            decimalValue = parseFloat(stringValue);
            decimalIndex = stringValue.indexOf('.');
            
            //Check if Minimum Number option is declared then compare
            if ((!isNaN(parseFloat(minimumNumber))) && (decimalValue < parseFloat(minimumNumber)))
            {
                returnObject.IsValid = false;
                returnObject.ErrorText = 'Value should be greater than or equal to ' + minimumNumber.toString();
            }
            //Decimal must be 11 digits with 2 decimals
            else if (decimalIndex > -1)
            {
                if (decimalIndex > 9)
                {
                    returnObject.IsValid = false;
                    returnObject.ErrorText = 'Value is too high';
                }
                else if ((stringValue.length - decimalIndex - 1) > 2)
                {
                    returnObject.IsValid = false;
                    returnObject.ErrorText = 'Too many decimal places';
                }
            }
            else if (stringValue.length > 9)
            {
                returnObject.IsValid = false;
                returnObject.ErrorText = 'Value is too high';
            }
        }
    }
    
    return returnObject;
}

//MJGE051611: Function to check if value is decimal
function IsDecimal(value)
{
    var reIsDecimal = /^\d*\.?\d+$/;
    
    if(reIsDecimal.test(value))
    {
        return true;
    }
    else
    {
        return false;
    }
}

//OMD11172010: Function to remove pipes '|' from a string
function RemovePipesFromString(controlId)
{
    var control = aspxGetControlCollection().Get(controlId);
    var strVal = "";
    if(control.GetValue() == null)
    {
        strVal = "";
    }
    else
    {
        
        strVal =  control.GetValue();
        strVal = strVal.replace(/\|/g,"");
    }
return strVal;
}


//CCE03302010: Function to get the java script timer for the card reader. 
function GetCardReaderTimer()
{
   var timeoutValue = 3000;
   return timeoutValue;
}

function CheckifObjectExist(objVal)
{
   if (document.getElementById(objVal) != null)
   {
     return true;
   }
   else
   {
    return false;
   }
}

function AddSelectedTickets() {
    MoveSelectedTickets(lstApplyToTickets, lstDoNotApplyToTickets);
    UpdateButtonState();
}
function AddAllTickets() {
    MoveAllTickets(lstApplyToTickets, lstDoNotApplyToTickets);
    UpdateButtonState();
}
function RemoveSelectedTickets() {
    MoveSelectedTickets(lstDoNotApplyToTickets, lstApplyToTickets);
    UpdateButtonState();
}
function RemoveAllTickets() {
    MoveAllTickets(lstDoNotApplyToTickets, lstApplyToTickets);
    UpdateButtonState();
}
function MoveSelectedTickets(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    dstListBox.BeginUpdate();
    var items = srcListBox.GetSelectedItems();
    for(var i = items.length - 1; i >= 0; i = i - 1) {
        dstListBox.AddItem(items[i].text, items[i].value);
        srcListBox.RemoveItem(items[i].index);
    }
    srcListBox.EndUpdate();
    dstListBox.EndUpdate();
}
function MoveAllTickets(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    var count = srcListBox.GetItemCount();
    for(var i = 0; i < count; i++) {
        var item = srcListBox.GetItem(i);
        dstListBox.AddItem(item.text, item.value);
    }
    srcListBox.EndUpdate();
    srcListBox.ClearItems();
}
function UpdateButtonState() {
    btnAddAll.SetEnabled(lstApplyToTickets.GetItemCount() > 0);
    btnRemoveAll.SetEnabled(lstDoNotApplyToTickets.GetItemCount() > 0);
    btnAdd.SetEnabled(lstApplyToTickets.GetItemCount() > 0);
    btnRemove.SetEnabled(lstDoNotApplyToTickets.GetItemCount() > 0);
}

//CCE01032010: Method to handle the events for the combo box in pricing schema module.
function PricingSchemaConstructStringForUpdate(eventDateId, sectionId, initialValue, hidPG, itemPGValue) 
{ 

if (hidPG.value != '')
{	
    //checks if value contains '%%' splitter (more than one section to update)
    if (hidPG.value.indexOf('%%') != -1)
    {		    
        var valuesArray = hidPG.value.split('%%');
        var valLength = valuesArray.length;
        var isNew = true;
        var isInitialValue = false;
        
        hidPG.value = '';
		
        var i = 0;	
        for (i = 0; i < valLength; i++)
        {
            var vArray = valuesArray[i].split(',');
            var mId = vArray[2];
            var dId = vArray[1];
            var vId = vArray[0];
    			
            if (mId == eventDateId && dId == sectionId && itemPGValue != initialValue)
            {
                //if Id's belong to the same dropdown and new value Id != initial value, replace vId with the new value Id
                vId = itemPGValue;
                isNew = false;
                isInitialValue = false;
            }
            else if (mId == eventDateId && dId == sectionId && itemPGValue == initialValue)
            {
                //if Id's belong to the same dropdown and new value Id = initial value, isInitialValue = true
                isNew = false;
                isInitialValue = true;
            }
            else
            {
                isInitialValue = false;
            }
    		
            if (hidPG.value != '' && isInitialValue == false)
            {
                hidPG.value += '%%' + vId + ',' + dId + ',' + mId;
            }
            else if (isInitialValue == false)
            {
                hidPG.value = vId + ',' + dId + ',' + mId;
            }
        }
		
		//if Id's are not found in the hidden field value (new Id's), Id's are concatenated  
        if (isNew && isInitialValue == false)
        {
            hidPG.value += '%%' + itemPGValue + ',' + sectionId + ',' + eventDateId;
        }
    }
    else //value does not contain a splitter (only one section to update)
    {
        var val = hidPG.value;
			
        var valArray = val.split(',')
        var mId = valArray[2];
        var dId = valArray[1];
        var vId = valArray[0];
			
        if (mId == eventDateId && dId == sectionId  && itemPGValue != initialValue)
        {
            //if Id's belong to the same dropdown and new value Id != initial value, replace vId with the new value Id
            vId = itemPGValue;
            hidPG.value = '';
            hidPG.value = vId + ',' + dId + ',' + mId;
        }
        else if (mId != eventDateId || dId != sectionId)
        {
            //if Id's are not from the same dropdown, Id's are concatenate
            hidPG.value += '%%' + itemPGValue + ',' + sectionId + ',' + eventDateId;
        }
        else
        {
            //if Id's belong to the same dropdown and new value Id = initial value, empty string is assigned to the hidden field value
            hidPG.value = '';
        }
    }		
}
else //new
{
    if (itemPGValue != initialValue)
    {
        hidPG.value = itemPGValue + ',' + sectionId + ',' + eventDateId;
    }
}


}

//MJGE100511: Issue 25839 - Function to insert/update data to hidden field for changes in Ticket Session Capacity
function TicketSessionCapacityConstructStringForUpdate(eventDateId, capacity, hdnTSC)
{
	var isExists = false;
	
	if (hdnTSC.value != '')
	{
		var eventDateArray = hdnTSC.value.split('|');
		hdnTSC.value = '';
		
		for (i = 0; i < eventDateArray.length; i++)
		{
			var capacityArray = eventDateArray[i].split(',');
			var eventDateIdStored = capacityArray[0];
			var capacityStored = capacityArray[1];
			
			if (eventDateId == eventDateIdStored && capacity != capacityStored)
			{
				capacityStored = capacity;
				isExists = true;
			}
			
			hdnTSC.value += ((hdnTSC.value == '')? '' : '|') + eventDateIdStored + ',' + capacityStored;
		}
	}
	
	if (!isExists)
	{
		hdnTSC.value += ((hdnTSC.value == '')? '' : '|') + eventDateId + ',' + capacity;
	}
}

//MJGE100511: Issue 25839 - Function to delete data from hidden field for changes in Ticket Session Capacity
function TicketSessionCapacityDeleteEntry(eventDateId, hdnTSC)
{
    if (hdnTSC.value != '')
    {
        var eventDateArray = hdnTSC.value.split('|');
		hdnTSC.value = '';
		
		for (i = 0; i < eventDateArray.length; i++)
		{
			var capacityArray = eventDateArray[i].split(',');
			var eventDateIdStored = capacityArray[0];
			var capacityStored = capacityArray[1];
			
			if (eventDateId == eventDateIdStored)
			    continue;
							
			hdnTSC.value += ((hdnTSC.value == '')? '' : '|') + eventDateIdStored + ',' + capacityStored;
		}
    }
}

function TicketSessionCapacityDisplayErrorMessage(newCapacity, capacity, booked, quantity, maxCapacity)
{
    var errorMessage = '';
    
    //No error if capacity didn't changed
    if (newCapacity == capacity)
        errorMessage = '';
    else if (newCapacity == null || newCapacity.trim() == '')
        errorMessage = 'Required';
    else if (newCapacity < booked)
        errorMessage = 'Capacity is less than sold';
    else if (IsNumeric(newCapacity))
    {
        if (newCapacity > maxCapacity)
            errorMessage = 'Capacity is too large';
        else if (!IsNumberDivisible(newCapacity, quantity, true))
            errorMessage = 'Capacity should be divisible by ' + quantity.toString();
    }
    else
        errorMessage = 'Invalid value';
        
    return errorMessage;
}

//MJGE110211: Issue 26055 - Added Function for checking of integer's divisibility
function IsNumberDivisible(dividend, divisor, isZeroAccepted)
{
    var isValid = true;
    
    if (dividend == 0)
    {
        isValid = (isZeroAccepted) ? true : false;
    }
    else
    {
        var mod = dividend % divisor;
        isValid = mod == 0;
    }
    
    return isValid;
}

//MJGE110211: Issue 25839 - Added Function for Validating Ticket Session Capacity
function IsTicketSessionCapacityValid(newCapacity, capacity, booked, quantity, maxCapacity)
{
    var isValid = true;
    
    if (!IsNumeric(newCapacity) || newCapacity > maxCapacity || newCapacity == capacity || newCapacity < booked || !IsNumberDivisible(newCapacity, quantity, true))
        isValid = false;   
    
    return isValid;
}

//Functions for the GC Promotion Code Settings
function AddSelectedGCType()
{
    MoveSelectedTickets(lstApply, lstNotApply);
    UpdateGCButtonState();
}
function AddAllGCType() {
    MoveAllTickets(lstApply, lstNotApply);
    UpdateGCButtonState();
}
function RemoveSelectedGCType() {
    MoveSelectedTickets(lstNotApply, lstApply);
    UpdateGCButtonState();
}
function RemoveAllGCType() {
    MoveAllTickets(lstNotApply, lstApply);
    UpdateGCButtonState();
}
function MoveSelectedGCType(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    dstListBox.BeginUpdate();
    var items = srcListBox.GetSelectedItems();
    for(var i = items.length - 1; i >= 0; i = i - 1) {
        dstListBox.AddItem(items[i].text, items[i].value);
        srcListBox.RemoveItem(items[i].index);
    }
    srcListBox.EndUpdate();
    dstListBox.EndUpdate();
}
function MoveAllGCType(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    var count = srcListBox.GetItemCount();
    for(var i = 0; i < count; i++) {
        var item = srcListBox.GetItem(i);
        dstListBox.AddItem(item.text, item.value);
    }
    srcListBox.EndUpdate();
    srcListBox.ClearItems();
}
function UpdateGCButtonState() {
    if(document.getElementById('ctl00_ContentPlaceHolder1_pageControlGCDiscount_btnAddAll') != null)btnAddAll.SetEnabled(lstApply.GetItemCount() > 0);
    if(document.getElementById('ctl00_ContentPlaceHolder1_pageControlGCDiscount_btnRemoveAll') != null) btnRemoveAll.SetEnabled(lstNotApply.GetItemCount() > 0);
    if(document.getElementById('ctl00_ContentPlaceHolder1_pageControlGCDiscount_btnAdd') != null)btnAdd.SetEnabled(lstApply.GetItemCount() > 0);
    if(document.getElementById('ctl00_ContentPlaceHolder1_pageControlGCDiscount_btnRemove') != null)btnRemove.SetEnabled(lstNotApply.GetItemCount() > 0);
}
//End of functions for GC Promotion Code Settings

//DAL091411: button function for ticket data collection
function AddSelectedItems() {
    MoveSelectedItems(lstApplyData, lstDoNotApplyData);
    UpdateCollectionButtonState();
}
function AddAllItems() {
    MoveAllItems(lstApplyData, lstDoNotApplyData);
    UpdateCollectionButtonState();
}
function RemoveSelectedItems() {
    MoveSelectedItems(lstDoNotApplyData, lstApplyData);
    UpdateCollectionButtonState();
}
function RemoveAllItems() {
    MoveAllItems(lstDoNotApplyData, lstApplyData);
    UpdateCollectionButtonState();
}
function MoveSelectedItems(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    dstListBox.BeginUpdate();
    var items = srcListBox.GetSelectedItems();
    for(var i = items.length - 1; i >= 0; i = i - 1) {
        dstListBox.AddItem(items[i].text, items[i].value);
        srcListBox.RemoveItem(items[i].index);
    }
    srcListBox.EndUpdate();
    dstListBox.EndUpdate();
}
function MoveAllItems(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    var count = srcListBox.GetItemCount();
    for(var i = 0; i < count; i++) {
        var item = srcListBox.GetItem(i);
        dstListBox.AddItem(item.text, item.value);
    }
    srcListBox.EndUpdate();
    srcListBox.ClearItems();
}
function UpdateCollectionButtonState() {
    if(document.getElementById('ctl00_ContentPlaceHolder1_ASPxPageControl1_btnAddAll') != null)btnAddAll.SetEnabled(lstApplyData.GetItemCount() > 0);
    if(document.getElementById('ctl00_ContentPlaceHolder1_ASPxPageControl1_btnRemoveAll') != null) btnRemoveAll.SetEnabled(lstDoNotApplyData.GetItemCount() > 0);
    if(document.getElementById('ctl00_ContentPlaceHolder1_ASPxPageControl1_btnAdd') != null)btnAdd.SetEnabled(lstApplyData.GetItemCount() > 0);
    if(document.getElementById('ctl00_ContentPlaceHolder1_ASPxPageControl1_btnRemove') != null)btnRemove.SetEnabled(lstDoNotApplyData.GetItemCount() > 0);
}
//end of button function for ticket data collection

//JMS110911: Checks if the string is a valid email format.
//NOTE: if the regex for email in the succeeding function (CheckIfValid(email))
//is changed, Constant BOOKING_EmailRegexValidationExpression must also be change.
function CheckIfValidEmail(email)
{
    var isValidEmail = /^\w+([\.]?[-!#\$%&'\*\+/=\?\^`\{\}\|~]*\w+)*@((\[(\d{1,3}\.){3}\d\])|(([0-9a-zA-Z]([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,6})$)/.test(email);
    
    return isValidEmail;
}
//End of check valid email function
