﻿/* ************************************************************************************ */
/* Change Log                                                                           */
/*                                                                                      */
/* 31-05-2011  - Richard Chapman - Deltasoft - Added                                    */
/* ************************************************************************************ */

// String support
function lefttrim(strvalue)
{
return (strvalue.replace(/^\s+/, ""));
}

function righttrim(strvalue)
{
return (strvalue.replace(/\s+$/, ""));
}

function trim(strvalue)
{
return strvalue.replace(/^\s+|\s+$/,"");
}

// XML Support
function XMLElement(success, data)
{
this.Success = success;
this.Data = data;
}

function XMLBuildElement(tag, data)
{
var element = '<' + trim(tag.toUpperCase()) + '>' + trim(data.toString()) + '</' + trim(tag.toUpperCase()) + '>';
return element;
}

function XMLGetElement(tag, xml)
{
    var starttag = "<" + tag + ">";
    var endtag = "</" + tag + ">";
    var result = new XMLElement(false, '');
    var startidx = xml.indexOf(starttag);
    if (startidx >= 0)
       {
       var endidx = xml.indexOf(endtag);
       if ((endidx >= 0) && (endidx > startidx))
          {
          result.Success = true;
          result.Data = xml.substring(startidx + starttag.length, endidx);
          }
       }
       
    return result;
}

// Members specific
function cli_performlogin(s, e)
{
var loginxml;

loginxml = XMLBuildElement('USERNAME', clitxtusername.GetText());
loginxml += XMLBuildElement('PASSWORD', clitxtpassword.GetText());
clicalnavcallback.SendCallback(XMLBuildElement('LOGIN', loginxml));
}

function cli_performlostpassword(s,e)
{
var loginxml;

loginxml = XMLBuildElement('USERNAME', clitxtlostusername.GetText());
clicalnavcallback.SendCallback(XMLBuildElement('LOST', loginxml));
}

function cli_membershipnavbar_headerclick(s, e)
{
e.processOnServer = false;
      
switch (e.group.name)
   {
   case 'join':
   case 'logout':
   case 'account':
   case 'members':
   case 'entry':
   case 'classification':
   case 'searchlink':
      clicalnavcallback.SendCallback(XMLBuildElement(e.group.name.toUpperCase(),''));
      break;
   case 'search':
          clitlmembersearch.PerformCustomCallback('0');
      break;
   }
   
// Collapse all groups except the current one
var idx, grp;
var maxidx = s.GetGroupCount();
for (idx = 0; idx < maxidx; idx++)
  {
  grp = s.GetGroup(idx);
  if (grp.index !== e.group.index)
    {
    if (grp.GetExpanded())
      grp.SetExpanded(false);
    }
  }
}

function clicalnavcallback_callbackcomplete(s, e)
{
var tag = XMLGetElement('LOGIN', e.result);
if (tag.Success)
   {
   // Look for a redirect tag, which means that the login was successful
   var result = XMLGetElement('REDIRECT', tag.Data);
   if (result.Success)
      {
      // Redirect on successful login
      window.location.href = result.Data;
      }
   else
      {
      // Check for an error response
      result = XMLGetElement('ERROR', tag.Data);
      if (result.Success)
         {
         clilblloginerror.SetText(result.Data);
         clilblloginerror.SetClientVisible(true);
         clitxtusername.Focus();
         }
      }
   }
else
    {
    tag = XMLGetElement('LOST', e.result);
    if (tag.Success)
        {
        // Check for an error response
        var result = XMLGetElement('ERROR', tag.Data);
        if (result.Success)
             {
             clilbllosterror.SetText(result.Data);
             clilbllosterror.SetClientVisible(true);
             clitxtlostusername.Focus();
             }
        else
             {
             clilbllosterror.SetClientVisible(false);
             }   
        }
    }
}

function cli_validatepassword (s, e)
{
var newpass, confirmpass;

newpass = clinofldnewpassword.GetText();
confirmpass = clinofldconfirmpassword.GetText();

newpass = trim(newpass.toLowerCase());
confirmpass = trim(confirmpass.toLowerCase());

if ((newpass.length > 0) || (confirmpass.length > 0))
    {
	e.isValid =(newpass == confirmpass);
	}
else
    {
	e.isValid = true;
	}
}

function cli_cbxunsuitable_checkchanged(s,e)
{
var state = s.GetChecked();
clilblsuggestion.SetVisible(state);
clilblnewclassification.SetVisible(state);
clitxtnewclassification.SetVisible(state);
clilblclassificationgroup.SetVisible(state);
clitxtclassificationgroup.SetVisible(state);
clibtnsubmit.SetVisible(state);
}

function cli_btnsubmit_click(s,e)
{
// If at least one of the input fields has an entry then callback to submit the entry via e-mail
var classification, group;

classification = clitxtnewclassification.GetText();
group = clitxtclassificationgroup.GetText();

classification = trim(classification);
group = trim(group);

if ((classification.length > 0) || (group.length > 0))
    {
	clicbsuggestion.PerformCallback('');
	}
}

function cli_cbsuggestion_callbackcomplete(s,e)
{
clicbxunsuitable.SetChecked(false);
cli_cbxunsuitable_checkchanged(clicbxunsuitable)
clitxtnewclassification.SetText('');
clitxtclassificationgroup.SetText('');
}

// Grid support
//
function cli_mouseover(visibleidx)
{
// Make the current row the row with focus
cligridview.SetFocusedRowIndex(visibleidx);
}

// News Control Support
//
function cli_nc_tailclick(s,e)
{
var htext = '';
if ((htext === '') && (typeof(clincnews) !== 'undefined'))
    {
    if (s === clincnews)
        htext = 'News';
    }
    
if (htext !== '')
   htext += ' details';
   
clipopresourcedetails.SetHeaderText(htext);
clipopresourcedetails.SetContentHTML('Loading...');
clipopresourcedetails.Show();
clicbresourcedetails.PerformCallback(e);
}

function cli_cbresourcedetails_callbackcomplete(s,e)
{
clipopresourcedetails.SetContentHTML(e.result);
}

// Search Filtering
//

function cli_txt_keyup(s,e)
{
var keyCode = e.htmlEvent.keyCode;
if(keyCode > 45 || keyCode == 8 || keyCode == 32)
    {
    cli_restarttimer();
    }
else if(keyCode == 13)
    cli_filterdvmembersearch();
}

var SearchFilterTimer=0;
function cli_restarttimer()
{
// If there is a timer already ticking then reset it
if (SearchFilterTimer != 0)
    window.clearTimeout(SearchFilterTimer);
    
// Set the timer for 500ms
SearchFilterTimer = window.setTimeout("cli_filterdvmembersearch()", 500);
}

function cli_filterdvmembersearch()
{
// Ensure that the search dataview is still loaded
if (typeof(clidvmembersearch) !== 'undefined')
    {
    if (!clidvmembersearch.InCallback())
        {
        clidvmembersearch.PerformCallback("Filter");
        }
    else
        {
        // Filter already in process so reset the timer for another go later
        cli_restarttimer();
        }
    }
}

function cli_tlmembersearch_nodeclick(s,e)
{
// If this is not the search page then perform a callback to redirect
if (typeof(clitxtclassification) == 'undefined')
    {
    if (typeof(clitlmembersearch) != 'undefined')
        {
        clitlmembersearch.PerformCustomCallback(e.nodeKey);
        }
    }
else
    {
    s.PerformCustomDataCallback(e.nodeKey);
    }
}

function cli_tlmembersearch_customdatacallback(s,e)
{
clitxtclassification.SetText(e.result);

// Force processing of the new search criteria
cli_restarttimer();
}

function cli_btnsearch_click(s,e)
{
// Callback to redirect to the search page
clicalnavcallback.SendCallback(XMLBuildElement('SEARCH',clitxtsearch.GetText()));
}

function cli_searchindex()
{
// Callback to redirect to the search index page
clicalnavcallback.SendCallback(XMLBuildElement('SEARCH',''));
}

function cli_txtsearch_keydown(s,e)
{
if (e.htmlEvent.keyCode == 13)
  {
  clibtnsearch.DoClick();
  }
}

// Edit Member News Control Items Support
//
// News Control Support
//
function formatdatetime(dt)
{
var result;

if (dt === null)
    {
    result = '';    
    }
else
    {
    var MMM = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    result = '#';
    result += (MMM[dt.getMonth()] + ' ');
    result += (dt.getDate() + ', ');
    result += (dt.getFullYear() + ' ');
    result += (dt.getHours() + ':');
    result += (dt.getMinutes() + ':');
    result += dt.getSeconds();
    result += '#';
    }
return (result);
}

function getresourcetype(s)
{
if (typeof(clincnews) !== 'undefined')
    {
    if (s === clincnews)
        return 1;
    }
    
return 0;
}

function getresourceclincobj()
{
var obj = undefined;

switch (clitabmemberentry.GetActiveTab().index)
    {
    case 1:
        {
        if (typeof(clincnews) !== 'undefined')
            {
            obj = clincnews;
            }
        break;
        } 
    }

return obj;
}

function cli_nc_edittailclick(s,e,editmode)
{
var htext = '';
switch (clitabmemberentry.GetActiveTab().index)
    {
    case 1:
        {    
        htext = 'News';
        break;
        }
    }
        
if (htext !== '')
   htext += ' details';
   
clipopeditdetails.SetHeaderText(htext);
clipopeditdetails.Show();

// If the edit mode for a new item, so nothing to load
if (editmode)
    {
    // Build the load tags
    var loadrec;
    //loadrec = XMLBuildElement("ID",e.name);
    loadrec = XMLBuildElement("ID",e);
    loadrec = XMLBuildElement("LOAD",loadrec);
    clicbeditdetails.PerformCallback(loadrec);
    }
else
    {
    // Clear the fields ready for a new entry
    ASPxClientEdit.ClearEditorsInContainerById('divresourcepanel');
    
    // The clear editors function does not appear to clear down ClientVisible="false" fields!
    clifldresourceattachment.SetText('');
    clifldresourceattachmenttype.SetText('');
    clifldresourceattachmentsize.SetText('');
    clifldresourceid.SetText('-1');
    
    // Default posting date to today
    clifldresourcepostdate.SetDate(new Date());
    }
    
// The delete button visibility is determined by the edit mode - hidden for new, visible for edit
clibtnresourcedelete.SetVisible(editmode);    
}

function cli_cbeditdetails_callbackcomplete(s,e)
{
var fldval;

fldval = XMLGetElement("LOAD",e.result);
if (fldval.Success)
    {
    fldval = XMLGetElement("ID",e.result);
    if (fldval.Success)
        {
        clifldresourceid.SetText(fldval.Data);
        }    
    fldval = XMLGetElement("TITLE",e.result);
    if (fldval.Success)
        {
        clifldresourcetitle.SetText(fldval.Data);
        }
    fldval = XMLGetElement("DESCRIPTION",e.result);
    if (fldval.Success)
        {
        clifldresourcedescription.SetText(fldval.Data);
        }
    fldval = XMLGetElement("POSTDATE",e.result);
    if (fldval.Success)
        {
        if (fldval.Data !== '')
            {
            clifldresourcepostdate.SetDate(new Date(fldval.Data));
            }
        else
            {
            clifldresourcepostdate.SetDate(null);
            }
        }
    fldval = XMLGetElement("EXPIRYDATE",e.result);
    if (fldval.Success)
        {
        if (fldval.Data !== '')
            {
            clifldresourcepostexpiry.SetDate(new Date(fldval.Data));
            }
        else
            {
            clifldresourcepostexpiry.SetDate(null);
            }        
        }
    fldval = XMLGetElement("FILE",e.result);
    if (fldval.Success)
        {
        /*clifldresourceattachmentfile.SetText(getoriginalfilename(fldval.Data));*/
        clifldresourceattachment.SetText(fldval.Data);
        }   
    fldval = XMLGetElement("TYPE",e.result);
    if (fldval.Success)
        {
        clifldresourceattachmenttype.SetText(fldval.Data);
        }      
    fldval = XMLGetElement("ORIGINAL",e.result);
    if (fldval.Success)
        {
        clifldresourceattachmentfile.SetText(fldval.Data);
        }               
    }
else
    {
    fldval = XMLGetElement("SAVE",e.result);
    if (fldval.Success)
        {
        if (fldval.Data !== '0')
            {
            clipopeditdetails.Hide();
            if (typeof(getresourceclincobj()) !== 'undefined')
                { 
                getresourceclincobj().PerformCallback('');
                }
            }
        }
    else
        {
        fldval = XMLGetElement("DELETE",e.result);
        if (fldval.Success)
            {
            if (fldval.Data !== '0')
                {
                clipopeditdetails.Hide();
                if (typeof(getresourceclincobj()) !== 'undefined')
                    { 
                    getresourceclincobj().PerformCallback('');
                    }
                }
            }        
        }
    }
}

function cli_mnuresourcecommands_itemclick(s,e)
{
// Force new resource
cli_nc_edittailclick(undefined,undefined,false);
}

function cli_btnresource_click(s,e)
{
if (s === clibtnresourcecancel)
    {
    // Cancelled - nothing to do
    clipopeditdetails.Hide();
    }
else if (s === clibtnresourcedelete)
    {
    // Delete resource
    var delrec;
    delrec = XMLBuildElement("ID",clifldresourceid.GetText());
    delrec += XMLBuildElement("RESOURCE",(clitabmemberentry.GetActiveTabIndex()).toString());    
    delrec = XMLBuildElement("DELETE",delrec);
    clicbeditdetails.PerformCallback(delrec);    
    }
else
    {
    // Save the current record
    if (ASPxClientEdit.ValidateEditorsInContainerById('divresourcepanel'))
        {
        var saverec;
        saverec = XMLBuildElement("ID",clifldresourceid.GetText());
        saverec += XMLBuildElement("RESOURCE",(clitabmemberentry.GetActiveTabIndex()).toString());    
        saverec = XMLBuildElement("SAVE",saverec);
        clicbeditdetails.PerformCallback(saverec);
        }
    }
}

// MemberClassifications Support
//
function cli_mnucommands_itemclick(s,e)
{
switch(e.item.name)
    {
    case 'classification':
        {
        //clitlclassifications.StartEditNewNode(clitlclassifications.GetFocusedNodeKey());
        clitlclassifications.PerformCustomDataCallback(clitlclassifications.GetFocusedNodeKey());
        break;
        }
    case 'group':
        {
        clitlclassifications.StartEditNewNode();
        break;
        }
    case 'delete':
        {
        clitlclassifications.DeleteNode(clitlclassifications.GetFocusedNodeKey());
        break;
        }
    }
}

function cli_tlclassifications_customdatacallback(s,e)
{
if (e.result !== '')
    {
    s.StartEditNewNode(e.result);
    }
}

function cli_membershipnavbar_expandedchanged(s,e)
{      
e.processOnServer = false;

if (e.group.GetExpanded())
    {
    switch (e.group.name)
        {
        case 'login':
        case 'lost':
            {
            // Force the focus to the username field, but delay things until current event chain finished, otherwise focus never gets set
            //window.setTimeout(function(){setcliobjfocus(e.group.name);},0);
            break;
            }
        }
    }
}

function setcliobjfocus(gn)
{
switch (gn)
    {
    case 'login':
        {
        if (typeof(clitxtusername) !== 'undefined')
            {
            clitxtusername.Focus();
            }
        break;
        }
    case 'lost':
        {
        if (typeof(clitxtlostusername) !== 'undefined')
            {
            clitxtlostusername.Focus();
            }
        break;
        }    
    }
}

function cli_attachmentupload_click(s,e)
{
cliattachmentupload.UploadFile();
}

function cli_attachmentupload_fileuploadcomplete(s,e)
{
if (e.isValid)
    {
    clifp.Hide();
    
    var fldval;

    fldval = XMLGetElement("UPLOAD",e.callbackData);
    if (fldval.Success)
        {
        fldval = XMLGetElement("FILE",e.callbackData);
        if (fldval.Success)
            {
            clifldresourceattachment.SetText(fldval.Data);
            /*clifldresourceattachmentfile.SetText(getoriginalfilename(fldval.Data));*/
            }
        fldval = XMLGetElement("TYPE",e.callbackData);
        if (fldval.Success)
            {
            clifldresourceattachmenttype.SetText(fldval.Data);
            }
        fldval = XMLGetElement("SIZE",e.callbackData);
        if (fldval.Success)
            {
            clifldresourceattachmentsize.SetText(fldval.Data);
            }
        fldval = XMLGetElement("ORIGINAL",e.callbackData);
        if (fldval.Success)
            {
            clifldresourceattachmentfile.SetText(fldval.Data);
            }            
        }
    }
}

/*function getoriginalfilename(f)
{
var uptr = f.indexOf('_');
if ( uptr >= 0)
    {
    uptr++;
    if (uptr < f.length)
        {
        return f.slice(uptr);
        }
    else
        {
        return f;
        }
    }
else
    {
    return f;
    }
}*/

function cli_classification_selectedindexchanged(s,e)
{
e.processOnServer = false;

if (s.GetSelectedIndex() == 0)
    {
    s.SetSelectedIndex(-1);
    clitlclassification.PerformCustomCallback('');
    clipcclassification.Show();
    }
}

function cli_btnclassification_click(s,e)
{
if (s === clibtnclassificationcancel)
    {
    // Cancelled - nothing to do
    clipcclassification.Hide();
    }
else
    {
    // Ensure that the updated entries are set in the classification list
    cliclassification.PerformCallback('');
    clipcclassification.Hide();    
    }
}

function cli_logoupload_click(s,e)
{
clilogoupload.UploadFile();
}

function cli_logoupload_fileuploadcomplete(s,e)
{
if (e.isValid)
    {
    clilp.Hide();
    
    var fldval = XMLGetElement("UPLOAD",e.callbackData);
    if (fldval.Success)
        {
        fldval = XMLGetElement("FILE",e.callbackData);
        if (fldval.Success)
            {
            var fn = fldval.Data;
            clifldlogo.SetText(fn);
            }
        fldval = XMLGetElement("TYPE",e.callbackData);
        if (fldval.Success)
            {
            clifldlogotype.SetText(fldval.Data);
            }
        fldval = XMLGetElement("PATH",e.callbackData);
        if (fldval.Success)
            {
            cliimglogo.SetImageUrl(fldval.Data + fn);
            }
        }
    }
}

function cli_description_keypress(s,e)
{
var keyCode = e.htmlEvent.keyCode;
if(keyCode > 45 || keyCode == 8 || keyCode == 32)
    {
    /* Determine the maximum length from the tooltip string */
    var tip = s.GetMainElement().title;
    var maxlen = tip.match(/\d+$/);
    if (isNaN(maxlen))
        {
        maxlen = 250;
        } 
    
    if (s.GetText().length >= maxlen)
        {
        e.htmlEvent.returnValue = false;
        }
    }
}

function cli_btncontact_click(s,e)
{
if (s === clibtncontactcancel)
    {
    // Cancelled - nothing to do
    clipopcontactdetails.Hide();
    }
else
    {
    // Save the current record
    if (ASPxClientEdit.ValidateEditorsInContainerById('divcontactpanel'))
        {
        var saverec;
        saverec = XMLBuildElement("ID",clifldcontactid.GetText());
        saverec = XMLBuildElement("CONTACT",saverec);
        clicbcontactdetails.PerformCallback(saverec);
        }
    }
}

function cli_cbcontactdetails_callbackcomplete(s,e)
{
clipopcontactdetails.Hide();
clipopmsgbox.Show();
window.setTimeout("clipopmsgbox.Hide()", 5000);
}

function cli_contactclick(id,organisation)
{
clifldcontactid.SetText(id);
clipopcontactdetails.SetHeaderText('Request contact from ' + organisation);
clipopcontactdetails.Show();
ASPxClientEdit.ClearEditorsInContainerById('divcontactpanel');
}

function cli_mnucommands_itemclick(s,e)
{
e.processOnServer = false;

switch(e.item.name)
    {
    case 'upload':
        {
        clifp.Show();
        break;
        }
    case 'delete':
        {
        break;
        }    
    }
}

function CheckParent(m)
{
    var inframe = false;

    if (top.location.pathname != "/Default.aspx")
       {
       if (m != "")
          {
          var s;
          if (self.location.search != "")
             {
             s = self.location.search + "&m=" + m;
             }
          else
             {
             s = "?m=" + m
             }
             
          top.location.href = "/Default.aspx" + s;
          }
       else
          {
          top.location.href = "/Default.aspx" + self.location.search;
          }
       }
    else
       {
       inframe = true;
       }
       
    return inframe;
}

function QueryString(parameter)
  { 
  var loc = location.search.substring(1, location.search.length);
  var param_value = false;

  var params = loc.split("&");
  for (i=0; i<params.length;i++)
     {
      param_name = params[i].substring(0,params[i].indexOf('='));
      if (param_name == parameter) 
         {
          param_value = params[i].substring(params[i].indexOf('=')+1)
         }
     }
  if (param_value)
    {
      return param_value;
    }
  else
    {
      return null; //Here determine return if no parameter is found
    }
}

function cli_tabmemberentry_activetabchanging(s,e)
{
// Validate the current tab before going to the next tab - user can step backwards but not forwards
var curtab = s.GetActiveTabIndex();
if (curtab < e.tab.index)
   {
   if (!ASPxClientEdit.ValidateEditorsInContainerById("pnlform" + curtab, ""))
      e.cancel = true;
   }
    
if (!e.cancel)    
   {
    // Set the dynamic elements of the Referees tab if necessary    
    if (e.tab.index == 2)
       {
       var tandc = jQuery('#ptandc').html();
       
       // If the tandc variable is empty then there is no terms and conditions (admin edir most likely) so do nothing
       if (tandc !== null)
           {
           tandc = tandc.replace('[MEMBERSHIP]',clihdstore.Get('Membership'));
           tandc = tandc.replace('[MEMBERSHIP]',clihdstore.Get('Membership'));
           jQuery('#ptandc').html(tandc);
           jQuery('#scontact').html(clifldcontact.GetText());
           jQuery('#scompany').html(clifldorganisation.GetText());       
           }
       }
   }
}

function cli_togglevisibility(s,trigger,lblname,fldname)
{
var visible = (s.GetText()==trigger);
lblname.SetClientVisible(visible);
fldname.SetClientVisible(visible);
}

function cli_btnnext_click(s,e)
{
var curtab = clitabmemberentry.GetActiveTabIndex();
if (ASPxClientEdit.ValidateEditorsInContainerById("pnlform" + curtab, ""))
    {
    clitabmemberentry.GetTab(++curtab).SetEnabled(true);
    clitabmemberentry.SetActiveTabIndex(curtab);
    }
}

function cli_validatevatno(s,e)
{
var vatno = jQuery.trim(s.GetText());
if (vatno.length == 0)
    {
    e.isValid = true;
    }
else
    {
    // Replace any embedded spaces
    vatno = vatno.replace(/\s/g,'');
    
    // The VAT number must be at least three characters in length
    if (vatno.length > 2)
        {
        // The first two characters must form the country code so now form the url request
        var vaturl = vatno.substr(0,2);
        vaturl += '/';
        vaturl += vatno.substr(2);
        vaturl = 'http://isvat.appspot.com/' + vaturl + '/?callback=?';
    
    
        jQuery.ajax({
                    url: vaturl, 
                    type: 'GET',
                    dataType: 'json',
                    success: function(data){vatresult(data);},
                    error: function(xmlhr){vatresult(false);},
                    async: false
                    }
                   );
        }                   
    }
}

function vatresult(data)
{
cliwtfldvatnumber.SetIsValid((data == true));
}
