/***************** Functions used in Create Activity Section ***********************/

var applicationContext = '';
/////////////////
var themeStore = null;
var headlineTitle = null;
var actDesc = null;
var locDesc = null;
var tempChosenId = null;
var tempDomElement = null;
var tt2 = null;
var themestoreALL = null;



function enableRSVP() {

    if(Ext.get('servicesSubView:servicesForm:rsvpServiceSubView:rsvpCheckBoxPastdate') == null) {
        Ext.get('servicesSubView:servicesForm:rsvpServiceSubView:rsvpCheckBox').dom.checked = true;
        Ext.get('servicesSubView:servicesForm:rsvpServiceSubView:rsvpCheckBox').dom.onclick.call();
    }



}

function disableRSVP() {


    if(Ext.get('servicesSubView:servicesForm:rsvpServiceSubView:rsvpCheckBoxPastdate') == null) {
        Ext.get('servicesSubView:servicesForm:rsvpServiceSubView:rsvpCheckBox').dom.checked = false;
        Ext.get('servicesSubView:servicesForm:rsvpServiceSubView:rsvpCheckBox').dom.onclick.call();
    }


}

  function populatePreview() {

      if(Ext.get("basicInfoSubView:CreateForm:description"))
      {
         actDesc = Ext.get("basicInfoSubView:CreateForm:description").getValue();
      }


       if(Ext.get("basicInfoSubView:CreateForm:name"))
       {    headlineTitle = Ext.get("basicInfoSubView:CreateForm:name").getValue();
       }

      if (Ext.get("basicInfoSubView:CreateForm:location"))
      {
            locDesc = Ext.get("basicInfoSubView:CreateForm:location").getValue();

      }

  }			

function changeSaveAsDraftButtonText(action) {
    var button = document.getElementById('CreateForm:saveAsDraftButton');
    if (action == 'save') {
        button.innerText = 'Auto Saving Draft';
        button.disabled = true;
    } else {
        button.disabled = false;
        button.innerText = 'Draft Auto Saved';
    }
}
function showInputTextForDateTime(inputTextID) {
    document.getElementById(inputTextID).style.display = 'block';
}

function hideInputTextForDateTime(inputTextID) {
    document.getElementById(inputTextID).style.display = 'none';
    document.getElementById(inputTextID).value = "";
}

function checkDate(inputTextID) {
    alert(document.getElementById(inputTextID).value);
    /*var formatString = "F d, Y h:i A";
    var startDate = new Date();
    var todaysDate = new Date();
    startDate.formatDate(formatString);
    startDate.getDate(document.getElementById(inputTextID).value);
    alert(todaysDate);
    alert(startDate);
    if (startDate < todaysDate) {
        var answer = confirm("You have selected a previous date. Are you sure you want to continue?");
        if (!answer) {
            document.getElementById(inputTextID).value = "";
        }
    }*/
}


function selectPicNoWindow(elem)
{
    unselectAll();
   var cbox = null;
   var component2 = Ext.get(elem);
   component2.addClass("selected-pic");
   cbox = Ext.get(component2).findParent("li" , 2 , true).down("input");
   cbox.dom.checked = true;
}

  function nl2br(text){
    text = escape(text);
    var re_nlchar = null;
    if(text.indexOf('%0D%0A') > -1){
		re_nlchar = /%0D%0A/g ;
	}else if(text.indexOf('%0A') > -1){
		re_nlchar = /%0A/g ;
	}else if(text.indexOf('%0D') > -1){
		re_nlchar = /%0D/g ;
	}
	return unescape( text.replace(re_nlchar,'<br />') );
}



function emailPreview() {
   if(Ext.getCmp("emailPrev") == null) {
    var emailPreviewWindow = new Ext.Window({contentEl: "previewEmailData" , id: 'emailPrev' , resizable:true , title: "Email Preview" , closeAction:'hide' , height: 550 , width:850});
    emailPreviewWindow.show();
    Ext.get("previewEmailData").show();
    javascript:scroll(0,0);
    Ext.getCmp("emailPrev").setPosition(330, 5);
       
   } else {
       Ext.getCmp("emailPrev").getUpdater().refresh();
       Ext.getCmp("emailPrev").show();
       javascript:scroll(0,0);
       Ext.getCmp("emailPrev").setPosition(330, 5);

   }

}

function unselectAll()
{
    if(Ext.get("templates"))
    {
        Ext.select("ul#templates li").each(function(target) {

            var child = target.dom;
              if(child.childNodes[0] != null && child.childNodes[1] != null) {
                child.childNodes[0].checked = false;
                child.childNodes[1].className = child.childNodes[1].className.replace("selected-pic", "pic-normal");
              }
        });
     }
    
}

function selectPic(component, numIn) {

    populatePreview();
    tempChosenId = numIn;
   

    var tpl = new Ext.XTemplate(
            '<tpl for=".">',
            '<div class="thumb-wrap" id="{id}" style="float:left;margin:0px;border:3px solid white;padding:2px;" id="{name}">',
            '<div class="thumb"><img  style="width:10em;" src="{imagepath}" title="{name}"></div>',
            '</div>',
            '</tpl>',
            '<div class="x-clear"></div>');

    


        if (!Ext.getCmp("bigWndw"))
        {
            tt2 = themestoreALL.getAt(themestoreALL.find("id", numIn));
            themestoreALL.clearFilter(true);
            themestoreALL.filter("theme_id", tt2.data.theme_id);

            new Ext.Window({id:"bigWndw" ,
                closeAction: "hide" , applyTo: "windowbig" ,
                contentEl: "bigholder" , title: "Choose a template" , shadow: false ,  modal: true ,
                autoCreate: true , constrain:true , constrainHeader:true , draggable: false ,
                plain:true , shim:false , 
                height: 770 , width: 700 ,
                bodyStyle: "background-color:white;" });

            Ext.get("bigholder").setStyle("display", "block");
            Ext.getCmp("bigWndw").show(true);

            Ext.getCmp("bigWndw").setPosition(330, 5);
            javascript:scroll(0,0);
            var themeSelectBox = new Ext.form.ComboBox({autoCreate: true , id: "themeSelectBoxCmb" , renderTo: "themeFamilyBox" , valueField: "theme_id" ,
                displayField: "themeName" , store: themeStore2 , mode: 'local' , style:"color:black;" , triggerAction: 'all' , editable: false });


            themeSelectBox.on("select", function(c, r, i) {

                themestoreALL.clearFilter(true);
                themestoreALL.filter("theme_id", r.data.theme_id);
                Ext.getCmp("themeview").setStore(themestoreALL);
                Ext.getCmp("themeview").refresh();

            });


            var panel = new Ext.Panel({
                id:'images-view',
                frame:true,
                applyTo: "themebox" ,
                width: 635 ,
                autoHeight:true,
                collapsible:true,
                layout:'fit',
                items: new Ext.DataView({
                    store: themestoreALL ,
                    tpl: tpl,
                    id: "themeview" ,
                    style:"background-color:white;" ,
                    autoHeight:true,
                    overClass:'x-view-over',
                    itemSelector:'div.thumb-wrap',
                    emptyText: 'No images to display'
                })
            });
            panel.render();


            Ext.get("inviteBox").setStyle("background", "url(" + tt2.data.imagepath + ") no-repeat 0px 60px");
			Ext.getCmp("themeSelectBoxCmb").setValue(tt2.data.theme_id);
        }
        else
        {
            Ext.getCmp("bigWndw").show(true);

            Ext.getCmp("bigWndw").setPosition(330, 5);
            javascript:scroll(0,0);
            tt2 = themestoreALL.getAt(themestoreALL.find("id", numIn));
            themestoreALL.clearFilter(true);
            themestoreALL.filter("theme_id", tt2.data.theme_id);
            Ext.getCmp("themeSelectBoxCmb").setValue(tt2.data.theme_id);
            Ext.getCmp("themeview").setStore(themestoreALL);
            Ext.getCmp("themeview").refresh();

            Ext.get("inviteBox").setStyle("background", "url(" + tt2.data.imagepath + ") no-repeat 0px 60px");
        }

        if(Ext.get("designSubView:DesignForm:imgupload_small") && Ext.get("designSubView:DesignForm:imgupload_small").dom != null && Ext.get("designSubView:DesignForm:imgupload_small").dom.src != "")
        {
            if(Ext.get('prevImg') == null)
            {
                Ext.get("imgSpot").createChild({tag: 'img' , id:'prevImg' ,  src: Ext.get("designSubView:DesignForm:imgupload_large").dom.src });
            }
            else
            {
                Ext.get("prevImg").dom.src =   Ext.get("designSubView:DesignForm:imgupload_large").dom.src ;
            }
         }

        Ext.select("li.themelink").on("click", function(e) {

            e.preventDefault();

        });

                                          

        Ext.getCmp("themeview").on("click", function(t, i, n, e) {
            var arrs = t.getNodes(0, themestoreALL.getCount());
            for (var ab in arrs)
            {
                try {
                if (arrs[ab] && ( typeof arrs[ab] == "object"))
                {
                    (arrs[ab]).setStyle("border:3px solid white");
                }
                }
                catch(err)
                {}
            }

           // Ext.getCmp("themeSelectBoxCmb").setValue(themestoreALL.getAt(i).data.theme_id);
            tempChosenId = n.id;
            Ext.get("inviteBox").setStyle("background", "url(" + themestoreALL.getAt(i).data.imagepath + ") no-repeat 0px 60px");

			
            if (Ext.get("designSubView:DesignForm:themes"))
            {
                var tt2 = themestoreALL.getAt(themestoreALL.find("id", tempChosenId));

                for (var bb in Ext.get("designSubView:DesignForm:themes").dom.options)
                {
                    try {
                    if(Ext.get("designSubView:DesignForm:themes") && Ext.get("designSubView:DesignForm:themes").dom && Ext.get("designSubView:DesignForm:themes").dom.options[bb]  )
                    {
                        if (tt2.data.theme_id == Ext.get("designSubView:DesignForm:themes").dom.options[bb].value)
                        {
                            Ext.get("designSubView:DesignForm:themes").dom.selectedIndex = bb;
                            Ext.get("designSubView:DesignForm:themes").dom.onchange();
                        }
                    }
                    }
                    catch(err)
                    {}
                }
            }
        });
    
    Ext.get("chooseBtn").on("click", function(e) {
        var foundIndex = 0;
        e.preventDefault();
        var flag = false;

        unselectAll();

        Ext.select("img.therightbox_" + tempChosenId).each(function() {
            selectPicNoWindow(this.dom);
            flag = true;
        });

        Ext.getCmp("bigWndw").hide();
    });
    
}

function enableTemplateMediaSubmitButton() {
    var fileField = document.getElementById('designSubView:uploadTemplateMediaView:uploadTemplateMediaForm:file');
    if (fileField.value != null) {
        if (isAnAllowedImageType(fileField.value.substring(fileField.value.lastIndexOf('.') + 1))) {
            document.getElementById('designSubView:uploadTemplateMediaView:uploadTemplateMediaForm:submitButton').disabled = false;
        } else {
            alert("Please select an image file.");
        }
    }
}

function enableProfilePictureSubmitButton(fileField, buttonId) {
    if (fileField.value != null) {
        if (isAnAllowedImageType(fileField.value.substring(fileField.value.lastIndexOf('.') + 1))) {
            document.getElementById(buttonId).disabled = false;
        } else {
            alert("Please select an image file.");
        }
    }
}
/***************** Functions used in Create Activity Section ***********************/

/***************** Popup window for Google Map ********************************/

function showMapWindow(latitude, longitude, location, googleMapKey) {
    var w = screen.availWidth;
    var h = screen.availHeight;

    var popW = 425, popH = 475;

    var leftPos = (w - popW) / 2, topPos = (h - popH) / 2;

    window.open(applicationContext+'/pages/includes/map.jsp?latitude=' + latitude + '&longitude=' + longitude + '&location=' + location + '&googleMapKey=' + googleMapKey + '', '' + location + '\'s Map', 'width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos + ',toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes');
}
/***************** Popup window for Google Map ********************************/
/***************** Functions used in Activity Media Section ********************************/
function enableActivityMediaSubmitButton() {
    var fileField = document.getElementById('activityMediaListView:uploadYourMediaView:uploadYourMediaForm:File');
    if (fileField.value != null) {
        if (!isAnAllowedMediaType(fileField.value.substring(fileField.value.lastIndexOf('.') + 1))) {
            alert("The type of file you are trying to upload is not supported.");
        } else {
            document.getElementById('activityMediaListView:uploadYourMediaView:uploadYourMediaForm:submitButton').disabled = false;
        }
    }
}
function isAnAllowedImageType(extension) {
    extension = extension.toLowerCase();
    return (extension in oc(['bmp','gif','jpe','jpeg','jpg','png','tif','tiff','wbmp']));
}
function isAnAllowedMediaType(extension) {
    if (isAnAllowedImageType(extension)) {
        return true;
    } else {
        extension = extension.toLowerCase();
        return (extension in oc(['mp3','flv','wav','wma','m4a','mp4','avi','mpeg','xvid','divx']));
    }
}
function oc(a)
{
    var o = {};
    for (var i = 0; i < a.length; i++)
    {
        o[a[i]] = '';
    }
    return o;
}
/***************** Functions used in Activity Media Section ********************************/

function changeEventPrivacyLevel(privacyLevelValue) {
    currentPrivactLevelValue = document.getElementById('basicInfoSubView:CreateForm:accessSettings').value;
    if (currentPrivactLevelValue != privacyLevelValue) {
        document.getElementById('basicInfoSubView:CreateForm:accessSettings').value = privacyLevelValue;
        if (privacyLevelValue == 3) {
            Richfaces.showModalPanel('privateEventPrivacyModalPanel');
        }
    }
}


function setAccessSettings(inputComponentValue, status) {
    if (inputComponentValue == 3 && status != "checked") {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="infoStyle">You have specified private access for this activity, it will only be visible to logged-in ti.ki users</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Private Access Level Confirmation Message');
        
        //alert("You have specified private access for this activity, it will only be visible to logged-in ti.ki users");
    }
    document.getElementById('basicInfoSubView:CreateForm:accessSettings').value = inputComponentValue;
}

function setSendNotificationStatus(inputComponentValue, status) {
    document.getElementById('accountSettingsForm:sendNotifications').value = inputComponentValue;
}

function makeInputTextReadOnlyFalse(obj) {
    obj.readOnly = true;
}


////////////////////////////////////////////////////////////////////////////////////
/**************************Modal Dialog By Imran Ansari Start**********************/

function showMessageDialog(message) {
    jQuery('body #jQueryMessageDialog').remove();
    jQuery('body').append('<div id="jQueryMessageDialog" style="display:none">' + message + '<br/><a class="cancelButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div>');
    showModalDialog('jQueryMessageDialog');
}

function changeModalDialogTitle(id, title) {
    if (document.getElementById(id) != null) {
        var selector = '#' + getJSFId(id);
        jQuery(selector + ' .title').remove();
        jQuery(selector).prepend('<div  class="title"><span>' + title + '</span></div>');
    }
}

function showModalDialog(id, title) {
    if (document.getElementById(id) != null) {
        //1. making modal by overlay
        jQuery('body .tiki_overlay').remove();
        jQuery('body').append('<div class="tiki_overlay" style="z-index:10000"></div>');
        //2. Show Dialog
        var selector = '#' + getJSFId(id);
        jQuery(selector).css('z-index', '10001').css('display', '').addClass('border_tiki_dialog');
        //3. Add Title to Dialog
        jQuery(selector + ' .title').remove();
        if ((title == null) || (title == '')) {
            title = 'ti&bull;ki';
        }
        jQuery(selector).prepend('<div  class="title"><span>' + title + '</span></div>');
    }
}

function showModalDialogRetainTitle(id) {
    if (document.getElementById(id) != null) {
        //1. making modal by overlay
        jQuery('body .tiki_overlay').remove();
        jQuery('body').append('<div class="tiki_overlay" style="z-index:10000"></div>');
        //2. Show Dialog
        var selector = '#' + getJSFId(id);
        jQuery(selector).css('z-index', '10001').css('display', '').addClass('border_tiki_dialog');
    }
}

function hideModalDialog(id) {
    if (document.getElementById(id) != null) {
        jQuery('body .tiki_overlay').remove();
        var selector = '#' + getJSFId(id);
        jQuery(selector).fadeOut();//.removeClass('border_tiki_dialog');
        //jQuery(selector).css('z-index', '-1').css('display', 'none');
        jQuery(selector + ' .title').remove();
    }
}

function hideModalDialogWithClearForm(id, formId) {
    if (document.getElementById(id) != null) {
        jQuery('body .tiki_overlay').remove();
        var selector = '#' + getJSFId(id);
        jQuery(selector).fadeOut();//.removeClass('border_tiki_dialog');
        //jQuery(selector).css('z-index', '-1').css('display', 'none');
        jQuery(selector + ' .title').remove();
        clearFormFields(formId);
    }
}

function showHideDialogAfterSubmit(isShow, id, title) {
    if (isShow + '' == 'true') {
        hideModalDialog(id);
    } else {
        showModalDialog(id, title);
    }
}

function showHideDialogAfterSubmitRetainTitle(isShow, id) {
    if (isShow + '' == 'true') {
        hideModalDialog(id);
    } else {
        showModalDialogRetainTitle(id);
    }
}


function controlModalPanel(isShow, modalPanelId) {
    if (isShow + '' == 'true') {
        Richfaces.hideModalPanel(modalPanelId);
    }
}


function clearModalPanel(isShow, modalPanelId, formId) {
    if (isShow + '' == 'true') {
        clearFormFields(formId);
        Richfaces.hideModalPanel(modalPanelId);
    }
}



function showHideDialogAfterSubmitWithClearFormAndOpenParentDialog(isShow, id, formId, parentId, parentTitle) {
    if (isShow + '' == 'true') {
        hideModalDialogWithClearForm(id, formId);
        showModalDialog(parentId, parentTitle);
    } else {
        showModalDialogRetainTitle(id);
    }
}

function showHideDialogAfterSubmitWithClearForm(isShow, id, formId) {
    if (isShow + '' == 'true') {
        hideModalDialogWithClearForm(id, formId);
    } else {
        showModalDialogRetainTitle(id);
    }
}

function getJSFId(id) {
    var ids = id.split(':');
    id = '';
    for (var i = 0; i < ids.length; i++) {
        id = id + ids[i];
        if (i < (ids.length - 1)) {
            id = id + '\\:';
        }
    }
    return id;
}

function fixIE() {

    if ((jQuery.browser) && (jQuery.browser.msie)) {
        alert(jQuery('[@position=fixed]'));
        jQuery('[@position=fixed]').css('position', 'absolute');
    }
}


function clearFormFields(formId) {
    var objForm = document.getElementById(formId);
    if (objForm) {
        for (var i = 0; i < objForm.elements.length; i++) {
            var objElement = objForm.elements[i];
			//alert(objElement.type + objElement.nodeName);
            if (objElement.type == "text" ||
                objElement.type == "password" || objElement.type == "textarea"
                    ) {
                objElement.value = '';
            }
        }
    }
    clearRichMessages();
}

function clearRichMessages() {
    jQuery('.rich-messages .rich-messages-label').remove();
    jQuery('.rich-message .rich-message-label').remove();
    jQuery('.rich-messages .rich-messages-marker').remove();
    jQuery('.rich-message .rich-message-marker').remove();
}

/**************************Modal Dialog By Imran Ansari Start**********************/
////////////////////////////////////////////////////////////////////////////////////

function submitCreateAtivityForm(formNumber) {
    var formNames = new Array('basicInfoSubView:CreateForm', 'designSubView:DesignForm', 'servicesSubView:servicesForm', '', 'invitationSubView:invitationForm');
    if ((formNumber <formNames.length) && (formNames[formNumber].length > 0)) {
        if (document.getElementById(formNames[formNumber]) != null) {
            document.getElementById(formNames[formNumber]).submit();
        }
    }
}

function resetCreateAtivityForms() {
    var formNames = new Array('basicInfoSubView:CreateForm', 'designSubView:DesignForm', 'servicesSubView:servicesForm', '', 'invitationSubView:invitationForm');
    for (var formNamesIterator = 0; formNamesIterator < formNames.length; formNamesIterator++) {
        if (formNames[formNamesIterator] != null && formNames[formNamesIterator].length > 0) {
            if (document.getElementById(formNames[formNamesIterator]) != null) {
                document.getElementById(formNames[formNamesIterator]).reset();
            }
        }
    }
}

//it is being called from create activity send invitation tab 5, when user types email in search box and then presses enter
function clickOnEnter(textAreaControl, evt, id) {
    if(textAreaControl.value.trim()!='') {
        evt = evt || window.event;
        var keyCode = evt.charCode ? evt.charCode : evt.keyCode ? evt.keyCode : 0;
        if (keyCode == 13) {
            var submit = document.getElementById(id);
            submit.click();
            return false;
        }
    }
    return true;
}

function deleteDefaultText(control, defaultText) {
    var controlTextValue = trim(control.value);
    if (controlTextValue == defaultText) {
        control.value = "";
        control.className = "normalTextClass";
    }
}

function restoreDefaultText(control, defaultText) {
    var controlTextValue = trim(control.value);
    if (controlTextValue == '') {
        control.value = defaultText;
        control.className = "defaultTextClass";
    } else if (controlTextValue == defaultText) {
        control.className = "defaultTextClass";
    } else {
        control.className = "normalTextClass";
    }
}

function trim(str) {
    var space = 0;
    if (str.length != 0) {
        for (i = 0; i <= str.length - 1; i++) {
            if (escape(str.charAt(i)) == escape(" ")) {
                space++;
            } else {
                break;
            }
        }
        if (space > 0) {
            str = str.substring(space, str.length);
        }
    }
    return str;
}

/**
 * This method stops page submission while enter is pressed
 * @param e keydown event
 */
function preventEnterKeySubmit(e) {
    if (e)
    {
        var target = (e && e.target) || (event && event.srcElement);
        if ((e.keyCode == 13) && ((target.tagName.toUpperCase() != 'textarea'.toUpperCase()) ||
                                  (target.type.toUpperCase() != 'textarea'.toUpperCase()))) {
            return false;
        }
    }
    return true;
}

function textCounter(field, maxlimit) {
    setTimeout("countCharactersCall('" + field.getAttribute('id') + "', '" + maxlimit + "')", 10);
}

function countCharactersCall(field, maxlimit) {
    var remainingCharacters = maxlimit - document.getElementById(field).value.length;
    if (remainingCharacters < 0) {
        document.getElementById(field).value = document.getElementById(field).value.substring(0, maxlimit);
        document.getElementById(field).scrollTop = document.getElementById(field).scrollHeight - document.getElementById(field).clientHeight;
        document.getElementById(field).scrollLeft = document.getElementById(field).scrollWidth - document.getElementById(field).clientWidth;
    }
}

function countCharactersCallWithTimeDisplay(field, maxlimit, cntfield) {
    var remainingCharacters = maxlimit - document.getElementById(field).value.length;
    if (remainingCharacters < 0) {
        document.getElementById(field).value = document.getElementById(field).value.substring(0, maxlimit);
        document.getElementById(field).scrollTop = document.getElementById(field).scrollHeight - document.getElementById(field).clientHeight;
        document.getElementById(field).scrollLeft = document.getElementById(field).scrollWidth - document.getElementById(field).clientWidth;
    }
    if (remainingCharacters >= 0) {
        document.getElementById(cntfield).innerHTML = remainingCharacters;
    } else {
        document.getElementById(cntfield).innerHTML = 0;
    }

}

function showPanel(panelToShow) {
    document.getElementById(panelToShow).style.display = 'block';
}

function hidePanel(panelToHide) {
    document.getElementById(panelToHide).style.display = 'none';
}

function textCounterWithCountDisplay(field, cntfield, maxlimit) {
    setTimeout("countCharactersCallWithTimeDisplay('" + field.getAttribute('id') + "', '" + maxlimit + "', '" + cntfield + "')", 10);
}

function writeTextIntoPreviewArea(field, cntfield) {
    var textAreaValue = document.getElementById(field).value;
    document.getElementById(cntfield).value = formatTextAreaString(textAreaValue, 18, " ");
}

function toggleSMSPreview() {
    if (document.getElementById('smsPreview') != null) {
        if (document.getElementById('smsPreview').style.display == 'block') {
            document.getElementById('smsPreview').style.display = 'none';
            document.getElementById('smsPreviewLineBreak').style.display = 'none';
        } else if (document.getElementById('smsPreview').style.display == 'none') {
            document.getElementById('smsPreview').style.display = 'block';
            document.getElementById('smsPreviewLineBreak').style.display = 'block';
        }
    }
}

function setFocus(id) {
    document.getElementById(id).focus();
}

function formatTextAreaString(smsText, breakPosition, separator) {
    var words = smsText.split(separator);
    var output = [];
    var x, w,cWord,tempWord;
    for (w = 0; w < words.length; w++)
    {
        cWord = words[w];
        if (cWord.length > breakPosition) {
            for (x = 0; x < cWord.length; x += breakPosition) {
                if (cWord.length - x < breakPosition) {
                    tempWord = cWord.substring(x);
                } else {
                    tempWord = cWord.substring(x, x + breakPosition);
                }
                output.push(tempWord);
            }
        } else {
            output.push(cWord);
        }
    }
    var finalSmsTextAreaString = "";
    for (w = 0; w < output.length; w++)
    {
        finalSmsTextAreaString += output[w] + separator;
    }
    return finalSmsTextAreaString;
}

function enableDisableReminderDaysBeforeDueDateDialogBox(checkBoxComponent) {
    var rsvpSelectMenuId = 'servicesSubView:servicesForm:rsvpServiceSubView:reminderDaysBeforeDueDate';
    if (checkBoxComponent.checked) {
        document.getElementById(rsvpSelectMenuId).disabled = false;
    }
    else {
        document.getElementById(rsvpSelectMenuId).disabled = true;
    }
}

//Rich Calendar Scripts

function changeClearToReset() {
    jQuery('div.rich-calendar-tool-btn').remove(":contains(\'Clean\')");
}

function changeClearToResetCheck() {
    jQuery('div.rich-calendar-tool-btn').remove(":contains(\'Clean\')");
    return true;
}

var offset = 0;
var rsvpOffset = 0;

function resetOffset() {
    offset = 0;
    rsvpOffset = 0;
}

function disableDatesBeforeStartDate() {
    if (offset > 41) {
        resetOffset();
    }
    var startDatePopup = document.getElementById("basicInfoSubView:CreateForm:startDate");
    var endDatePopup = document.getElementById("basicInfoSubView:CreateForm:endDate");
    jQuery('div.rich-calendar-tool-btn').remove(":contains(\'Clean\')");
    var curDate;

    var now = startDatePopup.component.selectedDate;

    if (now == null) {
        now = new Date();
    }

    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    now.setMilliseconds(0);
    curDate = endDatePopup.component.days[offset].date;
    if (curDate && curDate < now) {
        endDatePopup.component.dayCellClassName[offset] = "rich-calendar-cell-size rich-calendar-cell rich-calendar-boundary-dates";
    } else {
        endDatePopup.component.dayCellClassName[offset] = "rich-calendar-cell-size rich-calendar-cell rich-calendar-btn";
    }

    if (curDate.getDay() == 0 || curDate.getDay() == 6) {
        endDatePopup.component.dayCellClassName[offset] = "rich-calendar-cell-size rich-calendar-cell rich-calendar-holly rich-right-cell";
    }

    offset += 1;
    if (!curDate) {
        return false;
    }
    return (curDate >= now);
}

function disableDatesAfterStartDate() {
    if (rsvpOffset > 41) {
        resetOffset();
    }
    var rsvpStartDate = document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:startDate");
    var rsvpByDatePopup = document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:rsvpBy");
    jQuery('div.rich-calendar-tool-btn').remove(":contains(\'Clean\')");
    var curDate;
    var now = null;
    var todaysDate = new Date();
    todaysDate.setHours(0);
    todaysDate.setMinutes(0);
    todaysDate.setSeconds(0);
    todaysDate.setMilliseconds(0);
    if (rsvpStartDate.value != null && rsvpStartDate.value.length > 0) {
        now = new Date(rsvpStartDate.value);
    }
    if (now == null) {
        now = new Date();
    }
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    now.setMilliseconds(0);
    curDate = rsvpByDatePopup.component.days[rsvpOffset].date;
    if (curDate && (curDate < todaysDate || curDate > now)) {
        rsvpByDatePopup.component.dayCellClassName[rsvpOffset] = "rich-calendar-cell-size rich-calendar-cell rich-calendar-boundary-dates";
    } else {
        rsvpByDatePopup.component.dayCellClassName[rsvpOffset] = "rich-calendar-cell-size rich-calendar-cell rich-calendar-btn";
    }

    if (curDate.getDay() == 0 || curDate.getDay() == 6) {
        rsvpByDatePopup.component.dayCellClassName[rsvpOffset] = "rich-calendar-cell-size rich-calendar-cell rich-calendar-holly rich-right-cell";
    }

    rsvpOffset += 1;
    if (!curDate) {
        return false;
    }

    return !(curDate && (curDate < todaysDate || curDate > now));
}

function checkDobDate(){
	changeClearToReset();
}

function enableEndDateArea(showEndDateCheckBoxComponent) {
    var endDateIfIsEnabled = 'basicInfoSubView:CreateForm:endDateIfIsEnabled';
    if (showEndDateCheckBoxComponent.checked) {
        document.getElementById(endDateIfIsEnabled).style.display = "block";
    }
    else {
        document.getElementById(endDateIfIsEnabled).style.display = "none";
    }
}

function changeEndDateCorrespondingToStartDate() {
    var startDatePopup = document.getElementById("basicInfoSubView:CreateForm:startDate");
    var endDatePopup = document.getElementById("basicInfoSubView:CreateForm:endDate");
    var startDate = startDatePopup.component.selectedDate;
    var endDate = endDatePopup.component.selectedDate;
    if (endDate && startDate && endDate < startDate) {
        var endDateFinalDateString = startDate.formatDate("F d, Y");
        document.getElementById("basicInfoSubView:CreateForm:endDateInputDate").value = endDateFinalDateString;
    }
}

/*var startTimeIdValue = "";*/

function validateBasicInformationForm(formComponent, locationDefaultText, descriptionDefaultText) {
    try {
        var activityName = trim(document.getElementById(formComponent + ":name").value);
        /*
        var activityType = trim(document.getElementById(formComponent + ":eventTypeSOM").value);
        var activitySubType = trim(document.getElementById(formComponent + ":eventSubTypeSOM").value);
        */
        var activityStartDate = trim(document.getElementById(formComponent + ":startDateInputDate").value);
        var activityEndDate = trim(document.getElementById(formComponent + ":endDateInputDate").value);
        var activityStartTime = trim(document.getElementById(formComponent + ":startTime").value);
        var activityEndTime = trim(document.getElementById(formComponent + ":endTime").value);
        var inputTextFieldValue = trim(document.getElementById('basicInfoSubView:CreateForm:location').value);
        var textAreaFieldValue = trim(document.getElementById('basicInfoSubView:CreateForm:description').value);


        if (inputTextFieldValue == locationDefaultText) {
            document.getElementById('basicInfoSubView:CreateForm:location').value = "";
        }
        if (textAreaFieldValue == descriptionDefaultText) {
            document.getElementById('basicInfoSubView:CreateForm:description').value = "";
        }

        var status = true;
        var returnValue = "";
        var valTime = new RegExp("^[0-9]+:[0-9]+ [aApP]+[mM]+$");

        if (activityName == "") {
            status = false;
            jQuery('body #jQueryMessageDialog').remove();
            jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Please specify an activity name</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
            showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
            document.getElementById(formComponent + ":name").value = "";
            document.getElementById(formComponent + ":activityNameLabel").className = "errorStyle";
            document.getElementById(formComponent + ":name").focus();
        } else {
            document.getElementById(formComponent + ":activityNameLabel").className = "";
        }

        /*if (status && activityType == -1) {
            status = false;
            jQuery('body #jQueryMessageDialog').remove();
            jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Please specify an activity type</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
            showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
            document.getElementById(formComponent + ":activityTypeLabel").className = "errorStyle";
            document.getElementById(formComponent + ":eventTypeSOM").focus();
        }

        if (status && activitySubType == -1) {
            status = false;
            jQuery('body #jQueryMessageDialog').remove();
            jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Please specify an activity sub-type</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
            showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
            document.getElementById(formComponent + ":activityTypeLabel").className = "errorStyle";
            document.getElementById(formComponent + ":eventTypeSOM").focus();
        }*/

        if (status && activityStartDate != null && activityStartDate.length > 0) {
            returnValue = parseDate(activityStartDate, "F d, Y");
            if (returnValue == null) {
                status = false;
                jQuery('body #jQueryMessageDialog').remove();
                jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">"startDate" : Provided value is not a valid date/time</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
                showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
                document.getElementById(formComponent + ":startDateInputDate").value = "";
                document.getElementById(formComponent + ":startDateInputDate").focus();
            }
        }
        if (status && activityStartTime != -1 && activityStartTime != null && activityStartTime.length > 0) {
            if (!isValidTime(activityStartTime)) {
                status = false;
                jQuery('body #jQueryMessageDialog').remove();
                jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">"startTime" : Provided value is not a valid time</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
                showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
                document.getElementById(formComponent + ":startTime").value = "";
                document.getElementById(formComponent + ":startTime").focus();
            }
        }

        if (status && activityEndDate != null && activityEndDate.length > 0) {
            returnValue = parseDate(activityEndDate, "F d, Y");
            if (returnValue == null) {
                status = false;
                jQuery('body #jQueryMessageDialog').remove();
                jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">"endDate" : Provided value is not a valid date/time</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
                showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
                document.getElementById(formComponent + ":endDateInputDate").value = "";
                document.getElementById(formComponent + ":endDateInputDate").focus();
            }
        }

        if (status && activityEndTime != -1 && activityEndTime != null && activityEndTime.length > 0) {
            if (!isValidTime(activityEndTime)) {
                status = false;
                jQuery('body #jQueryMessageDialog').remove();
                jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">"endTime" : Provided value is not a valid time</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
                showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
                document.getElementById(formComponent + ":endTime").value = "";
                document.getElementById(formComponent + ":endTime").focus();
            }
        }
        var showEndDateCheckBoxComponent = document.getElementById("basicInfoSubView:CreateForm:reminderBooleanCheckBox");
        if (showEndDateCheckBoxComponent.checked) {
            if (status && (activityStartDate == "" || activityStartDate.length == 0) && activityEndDate != null) {
                status = false;
                jQuery('body #jQueryMessageDialog').remove();
                jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Please first select the start date</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
                showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
                document.getElementById(formComponent + ":endDateInputDate").value = "";
                document.getElementById(formComponent + ":endDateInputDate").focus();
            }

            if (status && activityStartDate != null && activityEndDate != null && activityStartTime != null && activityEndTime != null) {
                var startDateValue = new Date(activityStartDate + " " + activityStartTime);
                var endDateValue = new Date(activityEndDate + " " + activityEndTime);
                var dateDifference = startDateValue.getTime() - endDateValue.getTime();
                if (dateDifference > 0) {
                    status = false;
                    jQuery('body #jQueryMessageDialog').remove();
                    jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:35%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">End date is before start date</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
                    showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
                    document.getElementById(formComponent + ":endDateInputDate").value = "";
                    document.getElementById(formComponent + ":endDateInputDate").focus();
                }
            }
        } else {
            document.getElementById(formComponent + ":endDateInputDate").value = "";
            document.getElementById(formComponent + ":endTime").value = "";
        }
        /*
        if (!status) {
            document.getElementById('basicInfoSubView:CreateForm:location').value = locationDefaultText;
            document.getElementById('basicInfoSubView:CreateForm:description').value = descriptionDefaultText;
        }*/
    } catch(err) {

    }
    return status;
}

function isValidTime(timeStr) {
    // Checks if time is in HH:MM:SS AM/PM format.
    // The seconds and AM/PM are optional.
    var status = true;
    var timePat = /^(\d{1,2})(:\d{2})?(\s?(A|a|P|p).?(M|m).?)?$/;
    var matchArray = timeStr.match(timePat);
    if (matchArray == null) {
        status = false;
    }
    if (matchArray != null) {
        var hour = matchArray[1];
        var minute = matchArray[2];
        var ampm = matchArray[4];

        if (ampm == "") {
            ampm = null
        }

        if (hour < 0 || hour > 23) {
            status = false;
        }
        if (hour > 12 && ampm != null) {
            status = false;
        }
        if (minute < 0 || minute > 59) {
            status = false;
        }
    }
    return status;
}

function validateAccountSettingsForm() {
    var ok = true;
    var userName = trim(document.getElementById('accountSettingsForm:userName').value);
    var userEmail = trim(document.getElementById('accountSettingsForm:userEmail').value);
    var zipCode = trim(document.getElementById('accountSettingsForm:zipCode').value);
    var country = trim(document.getElementById('accountSettingsForm:countries').value);
    var mobilePhone = trim(document.getElementById('accountSettingsForm:mobilePhone').value);
    var dob = trim(document.getElementById('accountSettingsForm:dobInputDate').value);


//    if (userName == "") {
//        jQuery('body #jQueryMessageDialog').remove();
//        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Enter user name</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
//        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
//        document.getElementById('accountSettingsForm:userName').focus();
//        ok = false;
//    }

    if (ok && userEmail == "") {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Enter email</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById('accountSettingsForm:userEmail').focus();
        ok = false;
    }

    if (ok && !validateEmailAddress(userEmail)) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Enter valid email</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById('accountSettingsForm:userEmail').focus();
        ok = false;
    }

    if (ok && isNaN(zipCode)) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Enter valid zip code</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById('accountSettingsForm:zipCode').focus();
        ok = false;
    }

    if (ok && isNaN(mobilePhone)) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Enter valid mobile number</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById('accountSettingsForm:mobilePhone').focus();
        ok = false;
    }

    var d = parseDate(dob, "F d, Y");
    var thirteenYearsAgo = new Date();
    thirteenYearsAgo.setYear(thirteenYearsAgo.getYear()-13);
    if (d > thirteenYearsAgo){
        d = null;
    }
    if (ok && dob != "" && d == null) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">ti.ki is not intended for users below 13 years of age!</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById('accountSettingsForm:dobInputDate').focus();
        ok = false;
    }


    return ok;
}

function matchRegExp(curObj, re) {
    var ok = true;
    if (curObj.match(re) == null) {
        ok = false;
    }
    return ok;
}

function validateEmailAddress(curObj) {
    var re;
    re = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return matchRegExp(curObj, re);
}

function checkForValidRsvpDate() {
    var startDate = trim(document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:startDate").value);
    var rsvpByDate = trim(document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:rsvpByInputDate").value);
    var todaysDate = new Date();
    todaysDate.setHours(0);
    todaysDate.setMinutes(0);
    todaysDate.setSeconds(0);
    var ok = true;
    if (rsvpByDate != null && rsvpByDate.length > 0 && parseDate(rsvpByDate, "F d, Y") == null) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">The format for Rsvp date is not valid</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:rsvpByInputDate").focus();
        ok = false
    }

    var rsvpByDateValue = new Date(rsvpByDate);
    var startDateValue = new Date(startDate);
    startDateValue.setHours(0);
    startDateValue.setMinutes(0);
    startDateValue.setSeconds(0);

    var difference = todaysDate.getTime() - rsvpByDateValue.getTime();

    if (ok && rsvpByDateValue != null && difference > 1000) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">Date entered for RSVP is before today\'s date. Please retry!</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:rsvpByInputDate").focus();
        ok = false
    }

    difference = rsvpByDateValue.getTime() - startDateValue.getTime();

    if (ok && startDateValue != null && difference > 0) {
        jQuery('body #jQueryMessageDialog').remove();
        jQuery('body').append('<div id="jQueryMessageDialog" style="text-align: center;top:35%;left:28%;position:fixed;z-index:-1;display:none;"><div class="messagesArea"><span class="errorStyle">RSVP date specified is greater than activity start date</span><br/><br/><div align="center"><a class="closeButton" href="javascript:void(0);hideModalDialog(\'jQueryMessageDialog\');"></a>' + '</div></div></div>');
        showModalDialog('jQueryMessageDialog', 'Ti&bull;Ki Message');
        document.getElementById("servicesSubView:servicesForm:rsvpServiceSubView:rsvpByInputDate").focus();
        ok = false
    }
}

function showHideModalPanelOnComplete(button, show) {
    if (show) {
        button.form.style.visibility = 'hidden';
        button.form.previousSibling.style.visibility = 'visible';
    } else {
        button.form.style.visibility = 'visible';
        button.form.previousSibling.style.visibility = 'hidden';
    }
}

function showHideModalPanel(id, show) {
    if (show) {
        Richfaces.showModalPanel(id);
    } else {
        Richfaces.hideModalPanel(id);
    }
}

function showHideFormControlsModalPanel(button, hide) {
    if (hide) {
        button.form.style.visibility = 'hidden';
        button.form.previousSibling.style.visibility = 'visible';
    } else {
        button.form.style.visibility = 'visible';
        button.form.previousSibling.style.visibility = 'hidden';
    }
}

function showHideFormControlsModalPanelWithLoadingId(button, loadingImageId, hide) {
    if (hide) {
        button.form.style.visibility = 'hidden';
        document.getElementById(loadingImageId).style.visibility = 'visible';
    } else {
        button.form.style.visibility = 'visible';
        document.getElementById(loadingImageId).style.visibility = 'hidden';
    }
}

function abbreviateMonthName() {
    var divHtml = jQuery('td.rich-calendar-month').html();
    var divHtmlStartTag = divHtml.substr(0, divHtml.indexOf(">") + 1);
    var monthString = divHtml.substr(divHtml.indexOf(">") + 1);
    monthString = monthString.replace("</div>", "");
    var monthYear = monthString.split(",");
    var monthName = trim(monthYear[0]);
    var year = trim(monthYear[1]);

    if (monthName != null && monthName.length > 3) {
        monthName = monthName.substr(0, 3);
    }

    if (year != null && year.length == 4) {
        year = year.substr(2, 4);
    }

    var finalString = divHtmlStartTag + monthName + ", " + year + "</div>";
    jQuery('td.rich-calendar-month').html(finalString);
}

function disableDivWithInnerElements() {
    var innerDiv = document.getElementById("basicInfoSubView:CreateForm:innerDiv");
    var wrapperDiv = document.getElementById("basicInfoSubView:CreateForm:wrapperDiv");
    if (innerDiv != null && wrapperDiv != null) {
        wrapperDiv.style.position = "absolute";
        wrapperDiv.style.top = innerDiv.style.top;
        wrapperDiv.style.left = innerDiv.style.left;
        wrapperDiv.style.width = innerDiv.style.width;
        wrapperDiv.style.height = innerDiv.style.width;
        disableElement(innerDiv);
    }
}

function disableElement(el) {
    try {
    el.disabled = true;
    }
    catch(err)
    {}
    if (el.childNodes && el.childNodes.length > 0) {
        for (var x = 0; x < el.childNodes.length; x++) {
            disableElement(el.childNodes[x]);
        }
    }
}

// Functions used to restrict the user upto a given input length in text area
var lastValue;  //saves last text in canAddCharacter function, used in updateStatusText function

    function canAddCharacter(textAreaControl, e, preferredTextLength) {

        var keynum;
        if (window.event) // IE
        {
            keynum = e.keyCode;
        }
        else if (e.which) // Netscape/Firefox/Opera
        {
            keynum = e.which;
        }
    
        lastValue = textAreaControl.value;

        var allowedChars = new Array(8, 13, 37, 38, 39, 40, 46);	//Backspace, Line Feed (Enter), delete and arrow keys
        for (var x = 0; x < allowedChars.length; x++)
        {
            if (allowedChars[x] == keynum) {
                return true;
            }
        }
        return textAreaControl.value.length != preferredTextLength;
    }

    function updateStatusText(textAreaControl, textAreaStatusControlName, preferredTextLength) {

        if (textAreaControl.value.length > preferredTextLength) {
            //alert('text lenght exceeds..reverting');
            textAreaControl.value = textAreaControl.value.substring(0, preferredTextLength);
        }
        var prefix = textAreaControl.name.substring(0, textAreaControl.name.lastIndexOf(":") + 1);
        var taStatus = document.getElementById(prefix + textAreaStatusControlName);

        if (textAreaControl.value.length > preferredTextLength) { // If text is copied in text area
            textAreaControl.value = lastValue;
        }

        taStatus.innerHTML = "Characters Left: " + (preferredTextLength - textAreaControl.value.length);
        return false;
    }

// End of functions

/* Create Activity Send Invitations Already Invited Confirmation Popup */

function inviteAlreadyInvited(yes) {
    var email = document.getElementById('alreadyInvitedConfirmationEmail').innerHTML;
    var emails = document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmationEmails').value;

    if (yes) {
        //1. add current email to a separate email list
        var yessed = document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmed').value;
        if (yessed != '') {
            yessed += ',';
        }
        document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmed').value = yessed + email;
    }
    //2. is this current email is the last in emails list
    var commaIndex = emails.indexOf(',') ;
    if (commaIndex != -1) {//no it is not the last one,
        //3. exclude current email from emails list
        emails = emails.substr(commaIndex + 1, emails.length - commaIndex);
                    //4. now current email is the next one
        email = emails.split(',')[0];
        document.getElementById('alreadyInvitedConfirmationEmail').innerHTML = email;
        document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmationEmails').value=emails;
    } else {
        emails = '';
        document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:cancelToAllButton').click();
    }
}

function inviteAllAlreadyInvited(yesToAll) {
    var selectedInvitees = document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmed').value;
    document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmed').value = '';

    if (yesToAll) {
        if (selectedInvitees != '') {
            selectedInvitees += ',';
        }
        var emails = document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmationEmails').value;
        selectedInvitees += emails;//send data to server
    }
    document.getElementById('invitationSubView:alreadyInvitedConfirmationView:alreadyInvitedConfirmationForm:alreadyInvitedConfirmationEmails').value = selectedInvitees;
}
/**
 * createActivityBasicInfo.jsp.
 * This method decides whether to show the time options list or not.
 * 
 * @param timeOptions
 */
function showTimeOptions(timeOptions, focalControl) {
    if (timeOptions.style.display == '') {
        if (focalControl != timeOptions.id) {
            timeOptions.style.display = 'none';
        }
    }
}