/*global Ext, alert, document, SWFUpload, window, saveForm, frmTimeout, validatefrm, flNamesValidation, cancelForm, WidgetContainer, prompt */

var mBLAST = {};
Ext.namespace('mBLAST');
var maskHeight = 1900;

// for preloading images
mBLAST.imagePreloader = function () {
  var i, imageObj;
  imageObj = new Image();
  for (i = 0; i < mBLAST.preloadableImageArr.length; i = i + 1)
  {
    imageObj.src = mBLAST.preloadableImageArr[i];
  }
};

mBLAST.Init = function () {
  
  mBLAST.applicationName = "Ext.NET";
  mBLAST.handlerName = "mBJSONService.ashx";
  mBLAST.menuServiceMethod = "FetchMenu";
  mBLAST.impersonatedUserServiceMethod = "FetchImpersonatedUsers";
  mBLAST.userCompanyServiceMethod = "FetchUserCompanyList";
  mBLAST.publicationServiceMethod = "FetchPublication";
  mBLAST.HTTP = "";
  mBLAST.serverName = "";
  mBLAST.brandID = "";
  mBLAST.loginRedirectUrl = "";
  mBLAST.userFormUrl = "";
  mBLAST.companyFormUrl = "";
  mBLAST.defaultLink = "";
  mBLAST.pageUrl = "";
  mBLAST.formID = "";
  mBLAST.params = "";
  mBLAST.isValidCheck = "";
  mBLAST.urlExtension = "";
  mBLAST.searchFieldName = "";
  mBLAST.searchFieldId = "";
  mBLAST.searchFieldWidth = 250;
  mBLAST.searchFieldMaxLength = "";
  mBLAST.searchButtonText = "Search";
  mBLAST.searchPublicationParam = "strSearch";
  mBLAST.cancelButtonText = "Cancel";
	
	// main viewport
  mBLAST.mainLayout = '';
  mBLAST.mainLayoutEnabled = false;
	
	// tree, grid objects, etc.
  mBLAST.menuObjects = [];
  mBLAST.userObjects = [];
  mBLAST.companyObjects = [];
 
	// count upon which retry events should notify user...
  mBLAST.retryUIThreshhold = 5;
	
	// avoid multiple calls to onReady (legacy conversions)
  mBLAST.onReady = false;

  mBLAST.initPageLoad = 0;
  mBLAST.LoadingImage = "<img src='/images/spinner.gif' border='0' align='middle' alt=''>&nbsp;&nbsp;Please wait....";
  mBLAST.ReportProcess = "<img src='/images/spinner.gif' border='0' align='middle' alt=''>&nbsp;&nbsp;Please wait while we send this information to mBlast.";
  mBLAST.menuReady = false;
  mBLAST.menuReadyCount = 0;
  mBLAST.userReadyCount = 0;
  mBLAST.companyReadyCount = 0;
 
	// login timeout routines
  mBLAST.loginTimeout = "";
  mBLAST.sessionLimit = 1000 * 60 * 60; // 60 minutes
		
	// page mask related vars
  mBLAST.maskElement = {};
  mBLAST.uploadbox = null;

  // maximum characters allowed in textbox
  mBLAST.maxAllowedCharacter = 1024;
  
  // images to be preloaded
  mBLAST.preloadableImageArr = [
    '/images/spinner.gif',
    '/ext/resources/images/mblastlegacy/window/left-corners.png',
    '/ext/resources/images/mblastlegacy/window/right-corners.png',
    '/ext/resources/images/mblastlegacy/window/left-right.png',
    '/ext/resources/images/default/window/left-corners.png',
    '/ext/resources/images/default/window/right-corners.png',
    '/ext/resources/images/default/window/left-right.png',
    '/ext/resources/images/mblastlegacy/window/top-bottom.png',
    '/ext/resources/images/default/shadow-lr.png' 
  ];
  //to preload images
  mBLAST.imagePreloader();    
};

mBLAST.Init();

mBLAST.LoadPage = function () {

  if (mBLAST.serverName === "localhost") {
    mBLAST.HTTP = "http://";
  }
  else {
    mBLAST.HTTP = "https://";
  }
  
  if (mBLAST.urlExtension === ".asp") {
    mBLAST.userFormUrl = "/workspace/us_default.asp";
    mBLAST.companyFormUrl = "/workspace/co_default.asp";
    mBLAST.defaultLink = "/ws/default.asp";
  }
  else {
    mBLAST.userFormUrl = "/workspace/us_default.aspx";
    mBLAST.companyFormUrl = "/workspace/co_default.aspx";
    mBLAST.defaultLink = "/ws/default.aspx";
  }
  
  mBLAST.jsonMenuObjects();

};


mBLAST.LayoutOnReady = function (text) {
  // are we really ready? (and not already configed...)
  if (mBLAST.menuReady && !mBLAST.onReady)
  {
	
		// indicate we're configed...
    mBLAST.onReady = true;
		
		// when ready, define the viewport and display the grid...
    Ext.onReady(function () { 
	    mBLAST.mainLayoutDefine(); 
	  });		
		// ok to enable...
    mBLAST.mainLayoutEnabled = true;
		
		// finally, visible...
    mBLAST.mainLayoutEnable();
    
    if (mBLAST.pageUrl === "") {
      var wc = new WidgetContainer(111);
    }
    
    mBLAST.jsonUserObjects();
    mBLAST.jsonCompanyObjects();
	
    if (mBLAST.pageUrl !== "") {
      mBLAST.loadContent(mBLAST.pageUrl);
    }
	
  }
  else 
  {
	
    // disable viewport...
    mBLAST.mainLayoutDisable();
	
  }
	
};

mBLAST.centerRegion = new Ext.Panel({
  id: 'center',
  region: 'center',
  layout: 'fit',
  autoscroll : 'true',
  html : '<div style="height:100%; overflow:auto;" id="widgetContainer"><table border="0" cellspacing="0" cellpadding="0" width="100%"><tr id="subMenuBar"><td width="100%"></td></tr></table></div>',
  el : 'center-div'
});

mBLAST.mainLayoutDefine = function () {

  var htmlTable = '<table cellspacing="0" cellpadding="0" border="0" width="100%" style="background-image: url(/images/newui/top.gif);background-repeat: repeat-x;"><tbody><tr><td class="logo" style="padding-bottom:10px;"><a href="/default.asp"><img height="55" border="0" width="295" alt="mBLAST Home" src="http://www.mblast.com/images/newui/logo.gif"/></a></td><td> </td><td align="right" width="100%" class="upperright" style="white-space: nowrap;"><table cellspacing="4" cellpadding="0" border="0" width="100%"><tbody><tr><td align="right" style="white-space: nowrap;"> <a href="javascript:mBLAST.loadContent(\'/ws/personprofile/overview.aspx\');"><b>Setup</b></a>&nbsp;|&nbsp;<a href="javascript:mBLAST.loadContent(\'/workspace/support/overview.asp\')"><b>Help</b></a>&nbsp;|&nbsp;<a href="javascript:mBLAST.loadContent(\'/workspace/suggest/overview.asp\');"><b>Suggestions</b></a>&nbsp;|&nbsp;<a href="/workspace/logout.aspx"><b>Logout</b></a> </td></tr><tr><td align="right" style="white-space: nowrap;"><table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td align="right"><div id="userComboHolder" style="padding-right:10px;">';
  htmlTable += '<table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td align="right" style="white-space: nowrap; padding-right: 5px;"><a class="tmlink">User:</a> </td><td><form class="leftForm" action="' + mBLAST.userFormUrl + '" name="selusrfrm" method="post"><input type="text" name="ImpersonatedUserIDCtl" id="ImpersonatedUserIDCtl" class="tmlink" style="width:130px;"/><input type="hidden" name="ImpersonatedUserID" id="ImpersonatedUserID"/></form></td></tr></table></div></td><td align="right" style="padding-left:15px; "><div id="companyComboHolder" style="padding-right:10px;"><table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td align="right" style="white-space: nowrap; padding-right: 5px;"><a class="tmlink">Company:</a></td><td><form class="leftForm" action="' + mBLAST.companyFormUrl + '" name="selcompfrm" method="post"><input type="text" name="CompanyIdCtl" id="CompanyIdCtl" class="tmlink" style="width:260px;"/><input type="hidden" name="CoID" id="CoID"/> </form></td></tr></table></div></td><td align="right" style="white-space: nowrap; padding-left: 15px;">  <a>Live Help:</a> </td><td><script src="/CuteLiveSupport4/CuteSoft_Client/CuteChat/Support-Image-Button.js.aspx" type="text/javascript"/></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>';
  // main container gen...
  mBLAST.mainLayout = new Ext.Viewport(
  {
    layout: 'border',
    items: [
      new Ext.Panel(
      {
        id: 'north',
        region: 'north',
        el: 'north-div',
        height: 100,
        layout: 'fit',
        html: htmlTable,
        bbar: mBLAST.menuObjects
      }),
      mBLAST.centerRegion,
      new Ext.Panel(
      {
        id: 'south',
        region: 'south',
        layout: 'fit',
        el: 'south-div',
        height: 25,
        html: '<div style="padding-top: 3px;">&copy; 2000-2009 <a href="mailto:custservice@mblast.com">mBLAST, Inc.</a>&nbsp;&nbsp;<a href="/mk/terms_and_conditions/">Terms &amp; Conditions</a>&nbsp;&nbsp;<a href="javascript:createwin(\'/mk/privacy/\');">Privacy Policy</a></div>',
        style: 'text-align: center'
      })
    ]
  });

};


mBLAST.dynamicScript = function (response) {
  var source = response, scripts = [], statement = "", startTagStartPosition = "", startTagEndPosition = "", endTagStartPosition = "", endTagEndPosition = "";
  // Strip out tags
  while (source.toLowerCase().indexOf("<script") > -1 || source.toLowerCase().indexOf("</script") > -1) {
    startTagStartPosition = source.toLowerCase().indexOf("<script");
    startTagEndPosition = source.indexOf(">", startTagStartPosition);
    endTagStartPosition = source.toLowerCase().indexOf("</script", startTagStartPosition);
    endTagEndPosition = source.indexOf(">", endTagStartPosition);
    statement = source.substring(startTagEndPosition + 1, endTagStartPosition);
    // Add to scripts array
    if (statement !== "" && !statement.toLowerCase().match('<script') && !statement.match('gaJsHost') && !statement.match('pageTracker') && !statement.match('mBLAST.loginPopBox')) {
      scripts.push(source.substring(startTagEndPosition + 1, endTagStartPosition));
    }
    // Strip from source
    source = source.substring(0, startTagStartPosition) + source.substring(endTagEndPosition + 1);
  }
  return scripts.join(' ');
};

mBLAST.dynamicBodyScript = function (response) {
  var source = response, scripts = [], statement = "", startTagStartPosition = "", startTagEndPosition = "", onloadStartPosition = "", onloadTagEndPosition = "";
  // Strip out tags
  while (source.toLowerCase().indexOf("<body") > -1) {
    startTagStartPosition = source.toLowerCase().indexOf("<body");
    startTagEndPosition = source.indexOf(">", startTagStartPosition);
    statement = source.substring(startTagStartPosition, startTagEndPosition);
    // Add to scripts array
    if (statement !== "" && statement.toLowerCase().match('onload')) {
      statement = statement.replace(/\s/g, '');
      onloadStartPosition = statement.toLowerCase().indexOf("onload=");
      onloadTagEndPosition = statement.indexOf("\"", onloadStartPosition + 8);
      scripts.push(statement.substring(onloadStartPosition + 8, onloadTagEndPosition));
    }
    // Strip from source
    source = source.substring(0, startTagStartPosition) + source.substring(startTagEndPosition + 1);
  }
  return scripts.join(' ');
};

mBLAST.dynamicScriptFile = function (response) {
  var source = response, scriptFiles = [], statement = "", scriptStartPosition = "", scriptEndPosition = "", srcStartPosition = "", srcEndPosition = "", fileName = "";
  // Strip out tags
  while (source.indexOf("<script ") > -1) {
    scriptStartPosition = source.indexOf("<script ");
    scriptEndPosition = source.indexOf(">", scriptStartPosition);
    statement = source.substring(scriptStartPosition, scriptEndPosition);
    // Add to scripts array
    srcStartPosition = statement.indexOf("src=");
    srcEndPosition = statement.indexOf('.js', srcStartPosition);
    fileName = statement.substring(srcStartPosition + 5, srcEndPosition + 3);
    if (fileName !== "" && fileName.match('.js') && !fileName.match('page.js') && !fileName.match('mBLAST.js') && !fileName.match('ext-all.js') && !fileName.match('ext-base.js')) {
      scriptFiles.push(fileName);
    }
    source = source.substring(0, scriptStartPosition) + source.substring(scriptEndPosition + 1);
  }
  return scriptFiles;
};

mBLAST.loadJavascriptFile = function (file) {
  var head = document.getElementsByTagName('head').item(0), frmScript = document.createElement('script');
  frmScript.src = file;
  frmScript.type = 'text/javascript';
  frmScript.id = 'formScript';
  head.appendChild(frmScript);
};

mBLAST.setTitle = function (responseText) {
  var source, startTagStartPosition, startTagEndPosition, endTagStartPosition, endTagEndPosition;
  source = responseText;
  startTagStartPosition = source.toLowerCase().indexOf("<title");
  startTagEndPosition = source.indexOf(">", startTagStartPosition);
  endTagStartPosition = source.toLowerCase().indexOf("</title", startTagStartPosition);
  endTagEndPosition = source.indexOf(">", endTagStartPosition);
  if (startTagStartPosition > -1 && endTagStartPosition > -1) {
    document.title = source.substring(startTagEndPosition + 1, endTagStartPosition);
  }
};

mBLAST.loadJavascript = function (responseText) {

  var i = 0, fileList = mBLAST.dynamicScriptFile(responseText), head = "", frmScript = "", frmScript1 = "";
  mBLAST.setTitle(responseText);
  for (i = 0; i < fileList.length; i = i + 1) {
    mBLAST.loadJavascriptFile(fileList[i]);
  }
  head = document.getElementsByTagName('head').item(0);
  frmScript = document.createElement('script');
  frmScript.text = mBLAST.dynamicScript(responseText);
  frmScript.type = 'text/javascript';
  frmScript.id = 'formScript';
  head.appendChild(frmScript);
  frmScript1 = document.createElement('script');
  frmScript1.text = mBLAST.dynamicBodyScript(responseText);
  frmScript1.type = 'text/javascript';
  frmScript1.id = 'formScript';
  head.appendChild(frmScript1);
  
};

mBLAST.loadContent = function (pageUrl) {
  var wc;
  if (mBLAST.toolTip) {
    mBLAST.toolTip.hide();
  }
  if (mBLAST.initPageLoad > 0) {
    Ext.get(document.body).mask(mBLAST.LoadingImage);
    mBLAST.AjaxRequest(
    {
      url: pageUrl,
      method: "POST",
      params: mBLAST.params,
      form: mBLAST.formID,
      success: function (result, request) {
        var redirectUrl;
        mBLAST.downloadResourceUrl = undefined;
        if (document.getElementById('hiddenResponseDiv') !== null) {
          document.getElementById('hiddenResponseDiv').innerHTML = result.responseText;
          if (document.getElementById('downloadResourceUrl') !== null) {
            mBLAST.downloadResourceUrl = document.getElementById('downloadResourceUrl').value;
            document.getElementById('downloadResourceUrl').value = '';
                }
                if (document.getElementById('redirectToHomeUrl') !== undefined && document.getElementById('redirectToHomeUrl') !== null)
                {
                  mBLAST.redirectToHomeUrl = document.getElementById('redirectToHomeUrl').value;
                }
                if (document.getElementById('themeFileName') !== undefined && document.getElementById('themeFileName').value.search(/\S/) !== -1)
                {
                  Ext.util.CSS.swapStyleSheet('theme', '/ext/resources/css/' + document.getElementById('themeFileName').value);
                  document.getElementById('themeFileName').value = '';
          }
          Ext.get('hiddenResponseDiv').dom.innerHTML = '';
        }
        mBLAST.loginRedirectUrl = mBLAST.readCookie("LoginRedirectUrl");
        if (mBLAST.loginRedirectUrl !== null) {
          window.location.href = mBLAST.decode(mBLAST.loginRedirectUrl);
          mBLAST.eraseCookie("LoginRedirectUrl");
              }
              else if (mBLAST.redirectToHomeUrl !== undefined)
              {
                redirectUrl = mBLAST.redirectToHomeUrl;
                mBLAST.redirectToHomeUrl = undefined;
                mBLAST.loadContent(redirectUrl);
              }
              else {
          if (mBLAST.downloadResourceUrl !== undefined) {
            Ext.get(document.body).unmask();
                  redirectUrl = mBLAST.downloadResourceUrl;
                  mBLAST.downloadResourceUrl = undefined;
                  mBLAST.loadContent(redirectUrl);
                }
                else {
            if (mBLAST.centerRegion.body !== undefined) {
              mBLAST.centerRegion.body.update("<div id='cr' style='height:100%; overflow:auto;'>" + result.responseText + "</div><div id='hiddenResponseDiv' style='visibility:hidden; display:none'></div>");
            }
            mBLAST.loadJavascript(result.responseText);
            if (pageUrl.toLowerCase() === "/ws/" || pageUrl.toLowerCase().indexOf("/ws/default.aspx") !== -1 || pageUrl.toLowerCase().indexOf("/ws/default.asp") !== -1) {
              wc = new WidgetContainer(111);
            } else if (result.responseText.indexOf("WebPresenceDashboard") !== -1) {
              wc = new WidgetContainer(257);
            } else if (result.responseText.indexOf("AwardDashboard") !== -1) {
              wc = new WidgetContainer(15630);
            }
            Ext.get(document.body).unmask();
            mBLAST.loginPopBox(mBLAST.brandID);
          }
          mBLAST.formID = '';
          mBLAST.params = '';
        }
              if (document.getElementById('NavigationTree') && document.getElementById('NavigationTree').innerHTML === '') {
                mBLAST.navigationTree();
              }
      },
      failure: function (result, request) {
        mBLAST.errorWindow(result, request);
        Ext.get(document.body).unmask();
        mBLAST.loginPopBox(mBLAST.brandID);
        mBLAST.formID = '';
        mBLAST.params = '';
      }
    });
  }
  else {
    mBLAST.initPageLoad = 1;
    Ext.get(document.body).mask(mBLAST.LoadingImage);
    mBLAST.AjaxRequest(
    {
      url: pageUrl,
      method: "POST",
      params: mBLAST.params,
      form: mBLAST.formID,
      success: function (result, request) {
        mBLAST.loginRedirectUrl = mBLAST.readCookie("LoginRedirectUrl");
        if (mBLAST.loginRedirectUrl !== null) {
          window.location.href = mBLAST.decode(mBLAST.loginRedirectUrl);
          mBLAST.eraseCookie("LoginRedirectUrl");
        }
            else 
			{
          if (mBLAST.centerRegion.body !== undefined) {
            mBLAST.centerRegion.body.update("<div id='cr' style='height:100%; overflow:auto;'>" + result.responseText + "</div><div id='hiddenResponseDiv' style='visibility:hidden; display:none'></div>");
          }
          mBLAST.loadJavascript(result.responseText);
          if (pageUrl.toLowerCase() === "/ws/" || pageUrl.toLowerCase().indexOf("/ws/default.aspx") !== -1 || pageUrl.toLowerCase().indexOf("/ws/default.asp") !== -1) {
            wc = new WidgetContainer(111);
          } else if (result.responseText.indexOf("WebPresenceDashboard") !== -1) {
            wc = new WidgetContainer(257);
          } else if (result.responseText.indexOf("AwardDashboard") !== -1) {
            wc = new WidgetContainer(15630);
          }
          Ext.get(document.body).unmask();
          mBLAST.loginPopBox(3);
          mBLAST.formID = '';
          mBLAST.params = '';
        }
              if (document.getElementById('NavigationTree') && document.getElementById('NavigationTree').innerHTML === '') {
                mBLAST.navigationTree();
              }
      },
      failure: function (result, request) {
        mBLAST.errorWindow(result, request);
        Ext.get(document.body).unmask();
        mBLAST.loginPopBox(3);
        mBLAST.formID = '';
        mBLAST.params = '';
      }
    });
  }
};

mBLAST.errorWindow = function (result, request) {

  mBLAST.errorMsgBox = new Ext.Window({
    renderTo: document.body,
    title: 'Page could not be loaded',
    closable: true,
    closeAction: 'hide',
    width: 400,
    height: 180,
    border: false,
    plain: true,
    modal: true,
    items: [{html: '<div style="height:100px;overflow:auto">An unexpected error occured.<br><br> <b>URL : </b>' + request.url + '<br><br>Do you want to see the details?</div>'}],
    buttons: [new Ext.Button({ 
	    text: 'View HTML',
      handler: function () {
        mBLAST.innerErrorMsgBox = new Ext.Window({
          title: 'Page could not be loaded - HTML',
          border: false,
          region: 'center',
	        width: 410,
          height: 200,
          buttonAlign: 'center',
          items: new Ext.FormPanel({
            frame: false,
            border: false,
			      autoScroll: true,
	          width: 400,
            height: 135,
            bodyStyle: 'padding-top:10px',
            items: [{ 
              labelStyle: 'padding:5px;',
              xtype: 'label',
              text: result.responseText
            }]         
          }),
          draggable: false,
          buttons: [new Ext.Button({ 
            text: 'OK',
            handler: function ()       {
              mBLAST.innerErrorMsgBox.hide();
			      }
		      })]
        });
        mBLAST.innerErrorMsgBox.show();
	    }
    }),
      new Ext.Button({ 
        text: 'View Page',
        handler: function () { 
	        mBLAST.innerErrorMsgBox = Ext.MessageBox.show({
            title: 'Page could not be loaded - Page',
            msg: '<div style="height:200px;overflow:auto">' + result.responseText + '</div>',
            buttons: Ext.Msg.OK,
            width: 500,
            height: 600,
            closable: true
          });
        }
      }),
      new Ext.Button({ 
		    text: 'Close',
        handler: function () {
          mBLAST.errorMsgBox.hide(); 
		    }
      })]
    });
  mBLAST.errorMsgBox.show();
};

mBLAST.loadFormContent = function (form, param) {
  var pageUrl, formId = "id";
  if (form[formId] === undefined) {
    pageUrl = document.getElementById(form).action;
	  mBLAST.formID = form;
  }
  else {
    pageUrl = document.getElementById(form[formId]).action;
	  mBLAST.formID = form[formId];
  }
  mBLAST.params = param;
  mBLAST.loadContent(pageUrl + '?' + mBLAST.params);
};

mBLAST.hiddenFieldsQueryString = function (form) {
  
  var qString, el, i, formId = "id";
  
  el = document.getElementById(form[formId]).elements;
  
  qString = '';
  
  for (i = 0; i < el.length; i = i + 1) {
    if (el[i].type === 'hidden') {
      if (el[i].name !== 'OrderBy' && el[i].name !== 'OrderDirection' && el[i].name !== 'RecsPerPage' && el[i].name !== 'DocsPerPage') {
	      if (qString === '') {
	        qString += el[i].name + '=' + el[i].value;
	      }
	      else {
	        qString += '&' + el[i].name + '=' + el[i].value;
	      }
	    }
	  }
  }
  
  return qString;
  
};

mBLAST.FetchReportBoxInSearch = function (userID, searchText, searchType, strSrch) {
  mBLAST.reportDataChangesWindow(userID, searchText, searchType, strSrch, 'SEARCH');
};

mBLAST.FetchReportBoxOnForm = function (userID, formID, reportID) {
  mBLAST.reportDataChangesWindow(userID, formID, reportID, 'NORMALFORM');
};

mBLAST.FetchReportBox = function (userID, formID, reportID) {
  mBLAST.reportDataChangesWindow(userID, formID, reportID, 'UTILDISPLAYFORM');
};

mBLAST.reportChangesWindowForm = new Ext.FormPanel({
  frame: false,
  border: false,
  width: 395,
  height: 230,
  bodyStyle: 'padding-top:10px',
  defaults: { hideLabel: true },
  items: [
    {
      labelStyle: 'padding:5px;',
      xtype: 'label',
      text: 'Did you see something wrong with the information on this page? We would like to fix it. Please describe what is wrong in the box below.'
    },
	  {
      labelStyle: 'padding:5px;',
      xtype: 'textarea',
      id: 'Report',
      name: 'Report',
      height: 170,
      width: 350,
      style: 'margin-top:5px;',
      allowBlank: false,
      enableKeyEvents: true,
      listeners: {
        keyup: function (obj) {
          var strLen = 0;
          strLen = mBLAST.maxAllowedCharacter - obj.getValue().length;
          if (strLen < 0) {
            strLen = 0;
            Ext.get('Report').dom.value = Ext.get('Report').dom.value.substring(0, mBLAST.maxAllowedCharacter);
          }
          Ext.get('ReportInf').dom.innerHTML = strLen;
        }
      }
    },
    {
      labelStyle: 'padding:5px;',
      xtype: 'label',
      html: '<div style="float:left;width:110px;"/>Characters remaining: </div><div id="ReportInf" style="float:left;width:50px;"/>' + mBLAST.maxAllowedCharacter + '</div>'
    }
  ]
});

mBLAST.reportChangesWindowFormMsg = new Ext.FormPanel({
  frame: false,
  border: false,
  width: 395,
  height: 80,
  bodyStyle: 'padding-top:10px',
  defaults: { hideLabel: true },
  hide: true,
  items:
  [
    {
      labelStyle: 'padding:5px;',
      xtype: 'label',
      text: 'Thank you for submitting your data change to mBLAST. We will review and action your request within the next 24 hours, and will contact you if further information is required.'
    }
  ]
});

mBLAST.reportDataChangesSuccessWindow = function () {
  mBLAST.reportChangesSuccessWindow = new Ext.Window({
    applyTo: Ext.body,
    title: 'Report Data Changes',
    width: 405,
    height: 150,
    border: false,
    modal: true,
    draggable: false,
    resizable: false,
    items: [mBLAST.reportChangesWindowFormMsg],
    closeAction: 'hide',
    buttonAlign: 'center',
    buttons: [
      new Ext.Button({
        text: 'Ok',
        id: 'OkBtn',
        name: 'OkBtn',
        handler: function () {
          mBLAST.reportChangesSuccessWindow.hide();
        }
      })
    ]
  });
  mBLAST.reportChangesWindowFormMsg.show();
  mBLAST.reportChangesSuccessWindow.show();
};

mBLAST.reportDataChangesWindow = function () {
  // First four parameters for Search, Next three for Form popup Report Data Changes
  var funFlag = arguments[arguments.length - 1], userID, searchText, searchType, strSrch, formID, reportID;
    
  if (funFlag === 'SEARCH') {
    userID = (typeof (arguments[0]) !== undefined) ? arguments[0] : '';
    searchText = (typeof (arguments[1]) !== undefined) ? arguments[1] : '';
    searchType = (typeof (arguments[2]) !== undefined) ? arguments[2] : '';
    strSrch = (typeof (arguments[3]) !== undefined) ? arguments[3] : '';
  } 
  else if (funFlag === 'NORMALFORM' || funFlag === 'UTILDISPLAYFORM') 
  {
    userID = (typeof (arguments[0]) !== undefined) ? arguments[0] : '';
    formID = (typeof (arguments[1]) !== undefined) ? arguments[1] : '';
    reportID = (typeof (arguments[2]) !== undefined) ? arguments[2] : '';
  }
  mBLAST.reportChangesWindow = new Ext.Window({
    applyTo: Ext.body,
    title: 'Report Data Changes',
    width: 405,
    height: 300,
    border: false,
    modal: true,
    draggable: false,
    resizable: false,
    items: [mBLAST.reportChangesWindowForm],
    closeAction: 'hide',
    buttons: [
      new Ext.Button({
        text: 'Submit',
        id: 'Sbmt',
        name: 'Sbmt',
        triggerAction: 'all',
        handler: function () {
          if (Ext.get('Report').dom.value.search(/\S/) === -1) {
            Ext.get('Report').dom.value = '';
            Ext.get('ReportInf').dom.innerHTML = mBLAST.maxAllowedCharacter;
            Ext.Msg.alert('', 'Description is required. Please enter a value for it.');
          }
          else 
          {
            if (funFlag === 'SEARCH') {
              mBLAST.submitBugInSearch(userID, searchText, searchType, strSrch);
            } 
            else if (funFlag === 'NORMALFORM') 
            {
              mBLAST.submitBugOnForm(userID, formID, reportID);
            } 
            else if (funFlag === 'UTILDISPLAYFORM') 
            {
              mBLAST.submitBugUtilDisplayForm(userID, formID, reportID);
            }
          }
        }
      }),
      new Ext.Button({
        text: 'Cancel',
        id: 'Cancel',
        name: 'Cancel',
        triggerAction: 'all',
        handler: function () {
          mBLAST.reportChangesWindow.hide();
        }
      })
    ]
  });
  mBLAST.reportChangesWindowForm.show();
  mBLAST.reportChangesWindow.show();
  Ext.get('ReportInf').dom.innerHTML = mBLAST.maxAllowedCharacter;
  Ext.get('Report').dom.value = '';
  mBLAST.reportChangesWindowForm.getForm().reset();
};

mBLAST.submitBugInSearch = function (userID, searchText, searchType, strSrch) {
  mBLAST.reportChangesWindow.hide();
  Ext.get(document.body).mask(mBLAST.ReportProcess);
  var strReport = '';
  strReport = Ext.get('Report').dom.value;
  strReport = strReport.replace(/\n/g, '<br>');
  strSrch = strSrch.replace(/%2B/g, '+');
  // process via ext ajax...
  mBLAST.AjaxRequest({
    url: '/tm/sendbugtask.asp?Type=3&UserID=' + userID + '&Search=' + searchText + '&SearchType=' + searchType + '&Srch=' + strSrch + '&Report=' + strReport + '&rnd=' + Math.random(),
    params: '',
    success: function (result, request) {
      Ext.get(document.body).unmask(mBLAST.ReportProcess);
      mBLAST.reportDataChangesSuccessWindow();
    },
    failure: function (result, request) {
      Ext.get(document.body).unmask(mBLAST.ReportProcess);
      mBLAST.reportDataChangesSuccessWindow();
    }
  });
};

mBLAST.submitBugOnForm = function (userID, formID, reportID) {
  mBLAST.reportChangesWindow.hide();
  Ext.get(document.body).mask(mBLAST.ReportProcess);
  var strReport = '';
  strReport = Ext.get('Report').dom.value;
  strReport = strReport.replace(/\n/g, '<br>');
  // process via ext ajax...
  mBLAST.AjaxRequest({
    url: '/tm/sendbugtask.asp?Type=2&UserID=' + userID + '&FormID=' + formID + '&SessionID=' + reportID + '&Report=' + strReport + '&rnd=' + Math.random(),
    params: '',
    success: function (result, request) {
      Ext.get(document.body).unmask(mBLAST.ReportProcess);
      mBLAST.reportDataChangesSuccessWindow();
    },
    failure: function (result, request) {
      Ext.get(document.body).unmask(mBLAST.ReportProcess);
      mBLAST.reportDataChangesSuccessWindow();
    }
  });
};

mBLAST.submitBugUtilDisplayForm = function (userID, formID, reportID) {
  mBLAST.reportChangesWindow.hide();
  Ext.get(document.body).mask(mBLAST.ReportProcess);
  var strReport = '';
  strReport = Ext.get('Report').dom.value;
  strReport = strReport.replace(/\n/g, '<br>');
  // process via ext ajax...
  mBLAST.AjaxRequest({
    url: '/tm/sendbugtask.asp?Type=1&UserID=' + userID + '&FormID=' + formID + '&SessionID=' + reportID + '&Report=' + strReport + '&rnd=' + Math.random(),
    params: '',
    success: function (result, request) {
      Ext.get(document.body).unmask(mBLAST.ReportProcess);
      mBLAST.reportDataChangesSuccessWindow();
    },
    failure: function (result, request) {
      Ext.get(document.body).unmask(mBLAST.ReportProcess);
      mBLAST.reportDataChangesSuccessWindow();
    }
  });
};

// returns array of string json objects representing current menu status
mBLAST.jsonMenuObjects = function () {

  // process via ext ajax...
  mBLAST.AjaxRequest(
  {
    url: mBLAST.HTTP + mBLAST.serverName + "/" + mBLAST.applicationName + "/" + mBLAST.handlerName + "/" + mBLAST.menuServiceMethod,
    params: "urlExtension=" + mBLAST.urlExtension,
    success: function (result, request) { 
	    mBLAST.jsonMenuSuccess(result, request); 
	  },
    failure: function (result, request) { 
	    mBLAST.jsonMenuFail(result, request); 
	  }
  }
  );
};

// successful ajax call completion
mBLAST.jsonMenuSuccess = function (result, request) {

  // "compile" to array of strings...
  var menu = Ext.util.JSON.decode(result.responseText), i;
	
  // init menuObjects class instance
  mBLAST.menuObjects = [];
	
  // walk response "menu" list...
  for (i = 0; i < menu.length; i = i + 1) 
  {
	
    // spacer?
    if (menu[i] === "'-'") {
		
      // just add the spacer...
      mBLAST.menuObjects.push("-");
		
    }
    // no icon? - simple text...
    else if (menu[i].indexOf("iconCls", 0) === -1) 
    {
		
      // no sub object...
      mBLAST.menuObjects.push(Ext.util.JSON.decode(menu[i]));
		
    }
    else 
    {

      // "compile" menu def...
      mBLAST.menuObjects.push(Ext.util.JSON.decode("new Ext.Toolbar.SplitButton(" + menu[i] + ")"));
		
    }
	
  }
	
  // indicate we're ready...
  mBLAST.menuReady = true;
  
  // try to exec OnReady()...
  mBLAST.LayoutOnReady();
	
};

mBLAST.jsonMenuFail = function (result, request) {
	
  // inc retry counter...
  mBLAST.menuReadyCount = mBLAST.menuReadyCount + 1;
	
  // check for message user...
  if (mBLAST.menuReadyCount > mBLAST.retryUIThreshhold) 
  {
    // message user...
    mBLAST.AjaxRetry("Menu", function () { 
		  mBLAST.jsonMenuRetry(result, request); 
	  });
  }
  else 
  {
    // just retry...
    mBLAST.jsonMenuRetry();
  }
	
};

mBLAST.jsonMenuRetry = function (response) {
	
  // what did they decide?
  if (response === null) 
  {
    // re-start load attempts...
    mBLAST.jsonMenuObjects();
  }
  else if (response === "yes") 
  {
    // reset menu retry counter...
    mBLAST.menuReadyCount = 0;
    // re-start load attempts...
    mBLAST.jsonMenuObjects();
  }
	
};


// returns array of string json objects representing list of users
mBLAST.jsonUserObjects = function () {

  // process via ext ajax...
  mBLAST.AjaxRequest(
  {
    url: mBLAST.HTTP + mBLAST.serverName + "/" + mBLAST.applicationName + "/" + mBLAST.handlerName + "/" + mBLAST.impersonatedUserServiceMethod,
    success: function (result, request) { 
		  mBLAST.jsonUserSuccess(result, request); 
	  },
    failure: function (result, request) { 
		  mBLAST.jsonUserFail(result, request); 
	  }
  }
  );
};


// successful ajax call completion
mBLAST.jsonUserSuccess = function (result, request) {
  
  var impUsers, selectedUserKey = -1, comboFromUserArray, temp, i = 0;
    
  if (result.responseText === "") {
  
    document.getElementById('userComboHolder').style.display = "none";
    document.getElementById('userComboHolder').style.visibility = "hidden";
  }
  else  {
  
    impUsers = Ext.util.JSON.decode(result.responseText);

    while (i < impUsers.length) 
    {
	    temp = [];	
	    temp = [Ext.util.JSON.decode(impUsers[i]).userId, Ext.util.JSON.decode(impUsers[i]).userName, Ext.util.JSON.decode(impUsers[i]).selected];
	
	    mBLAST.userObjects[i] = temp;
	
	    i = i + 1;
    }
  
    comboFromUserArray = new Ext.form.ComboBox(
      {
        store: mBLAST.userObjects,
        typeAhead: true,
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a user...',
        selectOnFocus: true,
        applyTo: 'ImpersonatedUserIDCtl',
        editable: false,
        minListWidth: 140,
        listeners:	{
          select: function (combo, record, index) {
            document.getElementById('ImpersonatedUserID').value = combo.getValue();
            document.selusrfrm.submit();
          }
        }		
      }
    );

    selectedUserKey = mBLAST.ComboSelectedIndex(comboFromUserArray.store.data.items); // Find & Get default index value
    if (selectedUserKey !== - 1) {
      comboFromUserArray.setValue(selectedUserKey, ''); // Set default selected index
    }
  }

};


mBLAST.jsonUserFail = function (result, request) {
	
  // inc retry counter...
  mBLAST.userReadyCount = mBLAST.userReadyCount + 1;
	
  // check for message user...
  if (mBLAST.userReadyCount > mBLAST.retryUIThreshhold) 
  {
    // message user...
    mBLAST.AjaxRetry("Impersonated Users", function () { 
		  mBLAST.jsonUserRetry(result, request); 
	  });
  }
  else 
  {
    // just retry...
    mBLAST.jsonUserRetry();
  }
	
};

mBLAST.jsonUserRetry = function (response) {
	
  // what did they decide?
  if (response === null) 
  {
    // re-start load attempts...
    mBLAST.jsonUserObjects();
  }
  else if (response === "yes") 
  {
    // reset user retry counter...
    mBLAST.userReadyCount = 0;
    // re-start load attempts...
    mBLAST.jsonUserObjects();
  }
	
};


// returns array of string json objects representing list of users
mBLAST.jsonCompanyObjects = function () {

  // process via ext ajax...
  mBLAST.AjaxRequest(
  {
    url: mBLAST.HTTP + mBLAST.serverName + "/" + mBLAST.applicationName + "/" + mBLAST.handlerName + "/" + mBLAST.userCompanyServiceMethod,
    success: function (result, request) { 
		  mBLAST.jsonCompanySuccess(result, request); 
	  },
    failure: function (result, request) { 
		  mBLAST.jsonCompanyFail(result, request); 
	  }
  }
  );
};


// successful ajax call completion
mBLAST.jsonCompanySuccess = function (result, request) {
  
  var company, selectedCompanyKey = -1, comboFromCompanyArray, temp, i = 0;
    
  if (result.responseText === "") {
  
    document.getElementById('companyComboHolder').style.display = "none";
    document.getElementById('companyComboHolder').style.visibility = "hidden";
  }
  else  {
  
    company = Ext.util.JSON.decode(result.responseText);

    while (i < company.length) 
    {
	    temp = [];	
	    temp = [Ext.util.JSON.decode(company[i]).companyId, Ext.util.JSON.decode(company[i]).companyName, Ext.util.JSON.decode(company[i]).selected];
	
	    mBLAST.companyObjects[i] = temp;
	
	    i = i + 1;
    }
  
    comboFromCompanyArray = new Ext.form.ComboBox(
      {
        store: mBLAST.companyObjects,
        typeAhead: true,
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a company...',
        selectOnFocus: true,
        applyTo: 'CompanyIdCtl',
        editable: false,
        minListWidth: 140,
        listeners:	{
          select: function (combo, record, index) {
            document.getElementById('CoID').value = combo.getValue();
            document.selcompfrm.submit();
          }
        }		
      }
    );

    selectedCompanyKey = mBLAST.ComboSelectedIndex(comboFromCompanyArray.store.data.items); // Find & Get default index value
    if (selectedCompanyKey !== - 1) {
      comboFromCompanyArray.setValue(selectedCompanyKey, ''); // Set default selected index
    }
  }

};


mBLAST.jsonCompanyFail = function (result, request) {
	
  // inc retry counter...
  mBLAST.companyReadyCount = mBLAST.companyReadyCount + 1;
	
  // check for message user...
  if (mBLAST.companyReadyCount > mBLAST.retryUIThreshhold) 
  {
    // message user...
    mBLAST.AjaxRetry("Company", function () { 
		  mBLAST.jsonCompanyRetry(result, request); 
	  });
  }
  else 
  {
    // just retry...
    mBLAST.jsonCompanyRetry();
  }
	
};

mBLAST.jsonCompanyRetry = function (response) {
	
  // what did they decide?
  if (response === null) 
  {
    // re-start load attempts...
    mBLAST.jsonCompanyObjects();
  }
  else if (response === "yes") 
  {
    // reset company retry counter...
    mBLAST.companyReadyCount = 0;
    // re-start load attempts...
    mBLAST.jsonCompanyObjects();
  }
	
};


mBLAST.mainLayoutEnable = function (force)  { //Should check this parameter 'force' if its not required to be removed

  // un-mask the document object body...
  Ext.get(document.body).unmask();

};

mBLAST.mainLayoutDisable = function (message) {
	
  var body = Ext.get(document.body);
	
  // anything?
  if (body !== null)
  {
		
    // default message to ...
    if (message === undefined || message === null) {
      message = " is loading";
    }
		
    // mask the body of the document object...        
    body.mask("mBLAST" + message + "...", "x-mask-loading");
	
  }
	
};

mBLAST.AjaxRetry = function (message, callback) {

  // MODAL IS NOT FUNCTIONAL AS IT STANDS!!! - message performs a callback to fRetry function.
  Ext.MessageBox.show(
    {
      title: message + ' Operation Failed!',
      msg: 'The mBLAST ' + message + ' failed to complete, retry?',
      buttons: Ext.Msg.YESNO,
      icon: Ext.MessageBox.QUESTION,
      fn: callback,
      modal: false
    }
  );

};

// wrapper for all ext ajax calls, really handy for debugging...(for instance, wrapping success/fail functions to alternate path...)
mBLAST.AjaxRequest = function (o) {

  // call ext with object...
  Ext.Ajax.request(
  {
    url: o.url,
    params: o.params,
    success: o.success,
    failure: o.failure,
    timeout: 300000
  });
  return null;
};

mBLAST.Init = function () {

  mBLAST.serverName = document.location.hostname;

  // login timeout routines
  mBLAST.loginTimeout = "";
  mBLAST.sessionLimit = 1000 * 60 * 60; // 60 minutes

  // page mask related vars
  mBLAST.maskElement = {};
  mBLAST.uploadbox = null;

};

mBLAST.Init();

mBLAST.loginPopBox = function (brandId) {

  mBLAST.loginWindow = new Ext.Window({
    applyTo: Ext.body,
    title: 'Session Timeout',
    width: 405,
    border: false,
    items: new Ext.FormPanel({
      frame: false,
      border: false,
      width: 390,
      bodyStyle: 'padding-top:10px',
      items: [{
        layout: 'table',
        border: false,
        layoutConfig: {columns: 1},
        buttonAlign: 'center',
        items: [{
          labelStyle: 'padding:5px;',
          xtype: 'label',
          text : 'Your session has timed out. Please log back in to continue working. DO NOT refresh or navigate away from this page or you may lose any unsaved data.'
        }, {
          layout: 'form',
          url: 'login.aspx',
          frame: false,
          border: false,
          bodyStyle: 'padding:1px 0 0 15px;',
          buttonAlign: 'left',
          width: 390,
          defaults: {labelSeparator: '', width: '155px', align: 'left'},
          defaultType: 'textfield',
          items: [{
            fieldLabel: 'User name',
            name: 'PopLoginUID',
            id: 'PopLoginUID'
          }, {
            inputType: 'password',
            fieldLabel: 'Password',
            name: 'PopLoginPWD',
            id: 'PopLoginPWD'
          }, {
            inputType: 'hidden',
            name: 'LoginBrandID',
            id: 'LoginBrandID',
						value: brandId
          }]
        }, {
          bodyStyle: 'padding:0 0 5px 15px;',
          border: false,
          html: '<div id="loginError" class="popError"/></div><div style="clear:both"></div>'
        }],
        buttons: [{
				  text: 'Log In',
				  id: 'Sbmt_login',
				  name: 'Sbmt_login',
					handler: function () {
					  mBLAST.login();
					}
				}] 
      }]         
    }),
    closable : true,
    modal    : true,
    draggable: false,
    resizable: false,
    listeners: {
      close: function () {
        //window.location.href = "/workspace/logout.aspx";            
      },
      show: function (win) {
        if (this.modal) {
          this.mask.addClass('x-modal-dark-grey');
        }
      }
    }
  });
};

// This for Mblast submit window.

mBLAST.showSubmitWindow = function () {
  mBLAST.submitMsgBox = Ext.MessageBox.show({
    title: 'Saving Information',
    msg: '<img src="/images/spinner.gif" border="0" align="absmiddle">&nbsp;&nbsp;Please wait while we save this information.',
    closable: false,
    modal: false
  });
  mBLAST.showMask();
};

mBLAST.showMask = function () {
  if (document.body.offsetHeight < maskHeight || !Ext.isIE) {        
    Ext.getBody().mask();
  }
  else if (Ext.isIE) {
    var divCount, divTop, i;
    divCount = Math.ceil(document.body.offsetHeight / maskHeight);
    divTop = 0;
    for (i = 0; i < divCount; i = i + 1) {
      divTop = i * maskHeight;
      if (i === divCount - 1) {
        mBLAST.createMaskDiv(i + 1, divTop, document.body.offsetHeight - divTop);
      }
      else {
        mBLAST.createMaskDiv(i + 1, divTop, maskHeight);
      }
    }
  }
};



mBLAST.removeMask = function () {
  var i = 1;
  if (Ext.get('mask-div' + i))
  { 
    do {
      Ext.get('mask-div' + i).unmask();
      document.body.removeChild(document.getElementById("mask-div" + i));
      i = i + 1;
    }while (Ext.get('mask-div' + i));
  }
  else
  {
    Ext.getBody().unmask();
  }
};

mBLAST.createMaskDiv = function (seqNumber, divTop, divHeight) {
  var divId, newdiv;
  divId = "mask-div" + seqNumber;
  if (!document.getElementById(divId)) {
    newdiv = document.createElement('div');
    newdiv.setAttribute('id', divId);
    newdiv.style.width = document.body.offsetWidth;
    newdiv.style.height = divHeight + 'px';
    newdiv.style.position = "absolute";
    newdiv.style.left = '0px';
    newdiv.style.top = divTop + 'px';
    newdiv.style.zIndex = '5000';
    document.body.appendChild(newdiv);
    Ext.get(divId).mask();   
  }
};
mBLAST.hideSubmitWindow = function () {
  if (mBLAST.submitMsgBox !== undefined)
  {
    mBLAST.removeMask();
    mBLAST.submitMsgBox.hide();
  }  
};

// This for Mblast "Do you want to save this now?" window.

mBLAST.showSaveMsgBox = function () {
  mBLAST.saveMsgBox = Ext.MessageBox.show({
    title: 'Warning!',
    width: 400,
    msg: '<input type="hidden" name="Autosave" id="Autosave" value="N"><center>Do you want to save this now? If you wait too long to save, your session may time out and the information that you have entered will be lost.<br>Press "Ok" to save the form now and "Cancel" to continue editing.</center>',
    buttons: Ext.MessageBox.OKCANCEL,
    icon: Ext.MessageBox.QUESTION,
    closable: false,
    draggable: false,
    modal: false,
    fn: function (btn) {
      if (btn === 'ok')
      {
        saveForm();
      }
      else
      {
        cancelForm();
      }
    }
  });
  mBLAST.showMask();
};

mBLAST.hideSaveMsgBox = function () {
  
  if (mBLAST.saveMsgBox !== undefined) {
    mBLAST.removeMask();
    mBLAST.saveMsgBox.hide();
  }  
};

mBLAST.hideLoginWindow = function () {
  mBLAST.loginWindow.hide();
};

mBLAST.showLoginWindow = function () {
  mBLAST.loginWindow.show();
  if (document.getElementById('PopLoginUID') !== null)
  {
    document.getElementById('PopLoginUID').focus();
    document.getElementById('PopLoginUID').value = "";
  }
  if (document.getElementById('PopLoginPWD') !== null)
  {
    document.getElementById('PopLoginPWD').value = "";
  }
};

mBLAST.login = function () {

  var loginErr = {}, loginUID = '', loginPWD = '', loginBrandID = '';

  window.clearTimeout(mBLAST.loginTimeout);
  loginErr = document.getElementById('loginError');
  loginErr.innerHTML = '';
  loginErr.style.display = "none";

  loginUID = document.getElementById('PopLoginUID').value;
  loginPWD = document.getElementById('PopLoginPWD').value;
  loginBrandID = document.getElementById('LoginBrandID').value;

  // process via ext ajax...
  mBLAST.AjaxRequest({
    url: '/ws/sessionlogin.aspx?u=' + loginUID + '&p=' + loginPWD + '&b=' + loginBrandID + '&r=' + Math.random(),
    params: '',
    success: function (result, request) {
      if (result.responseText === '') {
        mBLAST.loginTimeout = window.setTimeout(mBLAST.showLoginWindow, mBLAST.sessionLimit);
        mBLAST.hideLoginWindow();
      } else {

        loginErr = document.getElementById('loginError');
        loginErr.innerHTML = result.responseText;
        loginErr.style.display = "block";
      }
    },
    failure: function (result, request) {
      mBLAST.result = result;
      mBLAST.request = request; 
      loginErr = document.getElementById('loginError');
      loginErr.innerHTML = '<a href="#" onclick="javascript:mBLAST.errorWindow(mBLAST.result, mBLAST.request)" style="text-decoration:none;color:#ff0000">Page error. Click to see the details</a>';
      loginErr.style.display = "block";
    }
  });
};


mBLAST.errorWindow = function (result, request) {
  mBLAST.errorMsgBox = Ext.MessageBox.show({
    title: 'Page could not be loaded',
    msg: 'An unexpected error occured.<br><br> <b>URL : </b>' + mBLAST.HTTP + mBLAST.serverName + request.url + '<br><br>Do you want to see the details?',
    buttons: Ext.Msg.YESNO,
    width: 400,
    height: 100,
    closable: true,
    fn: function (btn) {
      if (btn === 'yes')
      {
        mBLAST.innerErrorMsgBox = Ext.MessageBox.show({
          title: 'Page could not be loaded - Details',
          msg: '<div style="height:100px;overflow:auto">' + result.responseText + '</div>',
          buttons: Ext.Msg.OK,
          width: 500,
          height: 500,
          closable: true
        });
        mBLAST.errorMsgBox.close();
      }
    }
  });
};

mBLAST.createCookie = function (name, value, days) {
  var expires = "", date = "";
  if (days) {
    date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = name + "=" + value + expires + "; path=/";
};

mBLAST.readCookie = function (name) {
  var nameEQ = name + "=", ca = document.cookie.split(';'), c = "", i = "";
  
  for (i = 0; i < ca.length; i = i + 1) {
    c = ca[i];
	  while (c.charAt(0) === ' ') {
	    c = c.substring(1, c.length);
	  }
	  if (c.indexOf(nameEQ) === 0) {
	    return c.substring(nameEQ.length, c.length);
	  }
  }
  return null;
};

mBLAST.eraseCookie = function (name) {
	mBLAST.createCookie(name, "", -1);
};

mBLAST.decode = function (strUrl) {
	return decodeURIComponent(strUrl.replace(/\+/g, " "));
};

mBLAST.showToolTip = function (title, content) {
  var tooltipStyle, task;
  tooltipStyle = '';
  if (mBLAST.toolTip) {
    if (mBLAST.toolTipTitle !== title)
    {
      mBLAST.toolTip.hide();
      if (Ext.get('tooltip') !== null) {
        Ext.get('tooltip').remove();
      }      
    }
    else
    { 
      mBLAST.toolTip.show();
      return;
    }
  }
  mBLAST.toolTipTitle = title;
  if (document.getElementById('cr') !== null)
  {
    if (!Ext.isIE)
    {
      tooltipStyle = "position:relative;";
    }
    else
    {
      tooltipStyle = '';
    }    
  }
  else
  {
    tooltipStyle = '';
  }
  mBLAST.toolTip = new  Ext.ToolTip({
    id : 'tooltip',
    layout : 'anchor',
    html : "<div style='float:left;width:270px;' id='ext-tip-title'><b>" + title + "</b></div><div style='float:right;' class='x-tool x-tool-close' onclick='javascript:mBLAST.closeTip();'> <br></div><div style='clear:both'></div><div style='margin:0' id='ext-tip-content'>" + content + "</div>",
    anchor : 'top',
    anchorOffset : 10,
    autoHide : false,
    draggable : false,
    floating : true,
    shadow : false,
    style : (tooltipStyle !== '') ? tooltipStyle : this.style,
    anchorToTarget : false,
    modal : false
  });
  if (document.getElementById('cr') !== null)
  {
    mBLAST.toolTip.render("cr");
  }
  mBLAST.toolTip.targetXY = [Ext.EventObject.getPageX(), Ext.EventObject.getPageY() - 20];
  task = new Ext.util.DelayedTask(function () {
    mBLAST.toolTip.show();
  });
  task.delay(500);
};

mBLAST.closeTip = function () {
  mBLAST.toolTip.hide();
};

mBLAST.showPublicationWindow = function (Id) {
  mBLAST.publicationData = [];
  mBLAST.databaseId = Id;
  mBLAST.publicationGridStore = new Ext.data.Store({
    ownerCt: mBLAST,
    data: mBLAST.publicationData,
    reader: new Ext.data.ArrayReader({ id: 'id' }, [
      'recordId',
      'productName',
      'company',
      'description',
      'url',
      'relevance'
    ])
  });
  
  mBLAST.publicationGrid = new Ext.grid.GridPanel({
    region: 'center',
    autoScroll: true,
    frame: true,
    width: 715,
    height: 252,
    store: mBLAST.publicationGridStore,
    colModel: new Ext.grid.ColumnModel({
      defaults: {
        sortable: true
      },
      columns: [
        { header: "Publication", dataIndex: 'productName', width: 135 },
        { header: "Company", dataIndex: 'company', width: 135 },
        { header: "Description", dataIndex: 'description', width: 145 },
        { header: "URL", dataIndex: 'url', width: 155 },
        { header: "Relevance", dataIndex: 'relevance', width: 125, sortable: false }
      ]
    }),
    listeners: {
      cellclick: { scope: mBLAST, fn: mBLAST.updatePublication }
    }
  });
  
  mBLAST.searchTextBox = new Ext.form.TextField({
    //id: (mBLAST.searchFieldId !== '') ? mBLAST.searchFieldId : mBLAST.id + "_search-text",
    //name: (mBLAST.searchFieldName !== '') ? mBLAST.searchFieldName : mBLAST.id + "_search-text",
    width: mBLAST.searchFieldWidth,
    allowBlank: false,
    autoCreate: { tag: "input", maxLength: mBLAST.searchFieldMaxLength }
  });
  
  mBLAST.searchToolBar = new Ext.Toolbar({
    items: [
      {
        xtype: 'label',
        text: 'Search for:'
      },  
      mBLAST.searchTextBox,
      {
        xtype: 'tbspacer'
      },
      new Ext.Button({
        id: mBLAST.id + '_search-button',
        name: mBLAST.id + '_search-button',
        text: mBLAST.searchButtonText,
        listeners: {
          click: {scope: mBLAST, fn: mBLAST.searchPublication}
        }
      }),
      {
        xtype: 'tbspacer'
      },
      new Ext.Button({
        id: mBLAST.id + '_cancel-button',
        name: mBLAST.id + '_cancel-button',
        text: mBLAST.cancelButtonText,
        listeners: {
          click: {scope: mBLAST, fn: mBLAST.onClosePublicationWindow}
        }
      })
    ]
  });
  mBLAST.publicationWindow = new Ext.Window({
    applyTo: Ext.body,
    title: 'Publication Search',
    width: 727,
    height: 350,
    border: false,
    modal: true,
    draggable: false,
    resizable: false,
    tbar: mBLAST.searchToolBar,
    items: [mBLAST.publicationGrid],
    buttons: [{
      text: 'Close',
      listeners: {
        click: {scope: mBLAST, fn: mBLAST.onClosePublicationWindow}
      }
    }],
    listeners: {
      close: {scope: mBLAST, fn: mBLAST.onClosePublicationWindow}
    }
  });

  mBLAST.publicationWindow.show();

};

mBLAST.updatePublication = function (grid, rowIndex, colIndex, e) {
  var record, publicationId, publicationName, opt, ccount, itemFound, itemIndex, database;
  record = grid.getStore().getAt(rowIndex);
  publicationId = record.data.recordId;
  publicationName = record.data.productName;
  opt = document.createElement("option");
  database = document.getElementById(mBLAST.databaseId);
  itemFound = false;
  for (ccount = 0; ccount < database.options.length; ccount = ccount + 1) {
    if (database.options[ccount].value == publicationId) {
      itemFound = true;
      itemIndex = ccount;
    }
  }

  if (itemFound) {
    document.getElementById(mBLAST.databaseId).selectedIndex = itemIndex;
  }
  else {
  // Add an Option object to Drop Down/List Box
  document.getElementById(mBLAST.databaseId).options.add(opt);
  document.getElementById(mBLAST.databaseId).selectedIndex = (document.getElementById(mBLAST.databaseId).options.length - 1);
  // Assign text and value to Option object
  opt.text = publicationName;
  opt.value = publicationId;
  }
  mBLAST.onClosePublicationWindow();
};

mBLAST.searchPublication = function () {
  if (mBLAST.searchTextBox.isValid()) {
    mBLAST.loadPublicationStore();       // To load person store
  }
  else {
    Ext.Msg.alert("Error!", "Please enter your search text!");
  }
  return true;
};

mBLAST.loadPublicationStore = function () {
  var searchText, protocol; 
  protocol = document.location.protocol;
  if (protocol === 'http:')
  {
    protocol = 'http://';
  }
  // for secured url
  if (protocol === 'https:')
  {
    protocol = 'https://';
  }
  
  Ext.get(document.body).mask(mBLAST.LoadingImage);
  mBLAST.publicationGridStore.removeAll();
  searchText = mBLAST.searchTextBox.getValue();
  mBLAST.AjaxRequest({
  url: protocol + mBLAST.serverName + '/tm/pickpublication.asp?Format=1&Search=' + searchText,
    success: function (result, request) {
      mBLAST.publicationString = result.responseText;
      if (mBLAST.publicationString !== '[]') {
        mBLAST.populatePublicationData();
        Ext.get(document.body).unmask(mBLAST.LoadingImage);
      } else {
        Ext.Msg.alert("No Match!", "No records were found that match <b>[" + searchText + "]</b>.");
        Ext.get(document.body).unmask(mBLAST.LoadingImage);
      }
    },
    failure: function (result, request) {
      Ext.Msg.alert("Error!", "Page Request Failed. Try Later!");
      Ext.get(document.body).unmask(mBLAST.LoadingImage);
    }
  });
};

mBLAST.renderIcon = function (imageUrl) {
  return '<img src="' + imageUrl + '" border="0" align="middle" alt="" style="height:100px; width:100px;">';
};

mBLAST.populatePublicationData = function () {
  mBLAST.processPublicationData();       // To process the person records fetched via web service
  mBLAST.publicationGridStore.removeAll();
  mBLAST.publicationGridStore.loadData(mBLAST.publicationData); // To load te person grid store with fetched data
  mBLAST.publicationGrid.show();
};

mBLAST.processPublicationData = function () {
  mBLAST.personData = [];
  var tempArray = [], ccount, row;
  tempArray = mBLAST.jsonDecoder(mBLAST.publicationString);
  for (ccount = 0; ccount < tempArray.length; ccount = ccount + 1) {
    row = Ext.util.JSON.decode(tempArray[ccount]);
    mBLAST.publicationData[ccount] = [row.RecordId, row.ProductName, row.Company, row.Description, row.URL, row.Relevance];
  }
};

mBLAST.jsonDecoder = function (dataString) {
  return Ext.util.JSON.decode(dataString);
};

mBLAST.onClosePublicationWindow = function () {
  if (document.getElementById(mBLAST.databaseId)[document.getElementById(mBLAST.databaseId).selectedIndex].text === 'Select Publication')
  {
    document.getElementById(mBLAST.databaseId).selectedIndex = 0;
  }
  mBLAST.publicationWindow.hide();
};
mBLAST.showWindow = function (saveurl, Name) {
  mBLAST.ImageMapWindow = new Ext.Window({
    applyTo: Ext.body,
    title: 'Add publication to the Media That Matters List',
    width: 300,
    height: 100,
    border: false,
    modal: true,
    draggable: false,
    resizable: false,
    items:
    [
      {
        labelStyle: 'margin:5px;',
        xtype: 'label',
        text: 'Do you want to add ' + Name + ' to your Media That Matters list?'
      }
    ],
    closeAction: 'hide',
    buttons: [
      new Ext.Button({
        text: 'Yes',
        id: 'yes',
        name: 'yes',
        triggerAction: 'all',
        handler: function () {
          Ext.get(document.body).mask(mBLAST.LoadingImage);
          mBLAST.AjaxRequest({
            url: saveurl,
            params: '',
            success: function (result, request) {
              mBLAST.ImageMapWindow.hide();
              Ext.get(document.body).unmask(mBLAST.LoadingImage);
              mBLAST.reportDataChangesSuccessWindow();
            },
            failure: function (result, request) {
              Ext.get(document.body).unmask(mBLAST.LoadingImage);
              mBLAST.ImageMapWindow.hide();
              alert("Publication was not saved");
            }
          });
        }
      }),
      new Ext.Button({
        text: 'No',
        id: 'No',
        name: 'No',
        triggerAction: 'all',
        handler: function () {
          mBLAST.ImageMapWindow.hide();
        }
      })
    ]
  });
  mBLAST.ImageMapWindow.show();
}; 

mBLAST.doTrim = function (pmStr) {
  return pmStr.replace(/^\s+|\s+$/g, "");	
};

mBLAST.removeStringQuotes = function (pmStr) {
  var retStr = "";
  if (pmStr.charAt(0) === '"' && pmStr.charAt(pmStr.length - 1) === '"') {
    retStr = pmStr.substr(1, (pmStr.length - 2));
    return retStr;
  } else if (pmStr.charAt(0) === "'" && pmStr.charAt(pmStr.length - 1) === "'") {
    retStr = pmStr.substr(1, (pmStr.length - 2));
    return retStr;
  } else if (pmStr === 'true') {
    return true;
  } else if (pmStr === 'false') {
    return false;
  } else {
    return pmStr;
  }
};

mBLAST.jscriptCall = function (jscriptInputText) {
  var jscript = "", functionName = "", nameSpaceFuncName = "", funcWithReturn = false, functionGetParams = "", functionArgs = [], funcOption = 0, vIndex = 0;
  jscriptInputText = jscriptInputText.replace(/;/g, '');
  jscript = jscriptInputText.slice(7);
  if (jscript.indexOf('return ') !== -1) { 
    if (mBLAST.doTrim(jscript).indexOf('(') !== -1) {
      functionName = jscript.substr(0, mBLAST.doTrim(jscript).indexOf('('));
    } else {
      functionName = jscript;
    }
    functionName = functionName.slice(7);
    funcWithReturn = true;
  } else {
    jscript = mBLAST.doTrim(jscript);
    if (jscript.indexOf('(') !== -1) {
      functionName = jscript.substr(0, jscript.indexOf('('));
    } else {
      functionName = jscript;
    }
    funcWithReturn = false;
  }
  functionGetParams = jscript.substr(mBLAST.doTrim(jscript).indexOf('('), jscript.length);
  functionGetParams = mBLAST.doTrim(functionGetParams).replace(/\)/g, '');
  functionGetParams = mBLAST.doTrim(functionGetParams).replace(/\(/g, '');
  if (functionGetParams.indexOf(",") !== -1 && functionGetParams.length > 0) {
    functionArgs = functionGetParams.split(',');
    for (vIndex = 0;vIndex < functionArgs.length;vIndex = vIndex + 1) {
      functionArgs[vIndex] = mBLAST.removeStringQuotes(mBLAST.doTrim(functionArgs[vIndex]));
    }
    funcOption = 1;
  } else if (mBLAST.doTrim(functionGetParams) !== "") {
    functionArgs[0] = functionGetParams;
    funcOption = 1;
  }
  if (funcOption === 1) {
    if (functionName.indexOf("mBLAST") !== -1) {
      nameSpaceFuncName = functionName.slice(7);
      if (funcWithReturn) {
        return mBLAST[nameSpaceFuncName].apply(this, functionArgs);
      } else {
        mBLAST[nameSpaceFuncName].apply(this, functionArgs);
      }
    } else if (funcWithReturn) {
      return window[functionName].apply(this, functionArgs);
    } else {
      window[functionName].apply(this, functionArgs);
    }
  } else if (functionName.indexOf("mBLAST") !== -1) {
    nameSpaceFuncName = functionName.slice(7);
    if (funcWithReturn) {
      return mBLAST[nameSpaceFuncName].apply(this);
    } else {
      mBLAST[nameSpaceFuncName].apply(this);
    }
  } else if (funcWithReturn) {
    return window[functionName].apply(this);
  } else if (functionName !== "") {
    window[functionName].apply(this);
  }
};

mBLAST.jscriptElementFocus = function (elName) {
  var el = document.getElementById(elName);
  mBLAST.hideMessageBox();
  if (el) {
    el.focus();
  }
};

mBLAST.jscriptFormSubmit = function (frm) {
  mBLAST.hideMessageBox();
  mBLAST.loadFormContent(frm, '');
};

mBLAST.jscriptWindowLocation = function (sRedirectString) {
  sRedirectString = mBLAST.removeStringQuotes(sRedirectString);
  mBLAST.hideMessageBox();
  mBLAST.loadContent(sRedirectString);
};

mBLAST.jscriptTimeout = function (rowID) {
  mBLAST.hideMessageBox();
  setTimeout(function () {
    mBLAST.SetNoWinner(rowID);
  }, 100);
};

mBLAST.jscriptCreateWin = function (vlink) {
  mBLAST.hideMessageBox();
  mBLAST.createwin(vlink);
};

mBLAST.jscriptContactValidation = function () {
  if ((mBLAST.isEmpty(document.all.Subject.value) || mBLAST.isEmpty(document.all.Comments_Text.value))) { 
    document.all.ContactRequired.innerHTML = 'Please fill all the fields to send email';
    return false;
  } else { 
    mBLAST.sendMsgToAdmin();
  }
};

mBLAST.jscriptAdminEmailValidation = function () {
  if (mBLAST.isEmpty(document.all.AdminName.value) || mBLAST.isEmpty(document.all.AdminEmail.value) || !mBLAST.validateEmail(document.all.AdminEmail) || mBLAST.isEmpty(document.all.ProposeText.value)) { 
    if (!mBLAST.validateEmail(document.all.AdminEmail)) { 
      document.all.AdminRequired.innerHTML = 'Email is invalid'; 
    } else { 
      document.all.AdminRequired.innerHTML = 'Please fill all the fields to send email'; 
    }
    return false; 
  } else { 
    mBLAST.proposeAdmin(); 
  }
};

mBLAST.createwin = function (newpage) {
  var winDefaultLink = "", urlRegex = /http/i;
  if (urlRegex.test(newpage)) {
    window.open(newpage, "mblastwin" + Math.floor(Math.random() * 101), "height=580,scrollbars=yes,menubar=no,toolbar=no,location=no,resizable=yes,width=1050,top=10,left=10");
  } else {
    window.open(winDefaultLink + "?pageUrl=" + newpage, "mblastwin" + Math.floor(Math.random() * 101), "height=580,scrollbars=yes,menubar=no,toolbar=no,location=no,resizable=yes,width=1050,top=10,left=10");
  }
};

mBLAST.validateEmail = function (fld) {
	
  var pass = true, emailPat = "", specialChars = "", validChars = "", quotedUser = "", atom = "", word = "", userPat = "",  matchArray = "", i, atomPat = "", domArr = "", len = "", domain = "", user = "";
	emailPat = new RegExp("^(.+)@(.+)$");
	specialChars = "\\(\\)><@#+=/$|,!?'%&*{}^\\;:\\\\\\\"\\.\\[\\]";
	validChars = "[^\\s" + specialChars + "]";
	quotedUser = "(\"[^\"]*\")";
	atom = validChars + '+';
	word = "(" + atom + "|" + quotedUser + ")";
	userPat = new RegExp("^" + word + "(\\." + word + ")*$");
	matchArray = fld.value.match(emailPat);

  pass = (matchArray !== null);
  if (pass) {
    user = matchArray[1];
    for (i = 0; i < user.length; i = i + 1) {
      if (user.charCodeAt(i) > 127) {
        pass = false;
      }
    }
  }
  if (pass) {
    domain = matchArray[2];
    for (i = 0; i < domain.length; i = i + 1) {
      if (domain.charCodeAt(i) > 127) {
        pass = false;
      }
    }
  }
  if (pass && !user.match(userPat)) {
    pass = false;
  }
  if (pass) {
    atomPat = new RegExp("^" + atom + "$");
    domArr = domain.split(".");
    len = domArr.length;
    for (i = 0; i < len; i = i + 1) {
      if (domArr[i].search(atomPat) === -1) {
        pass = false;
      }
    }
  }
  if (pass && len < 2) {
    pass = false;
  }

  if (!pass) {
    alert('Error: "Email address" is incomplete or contains invalid values.');
    if (!fld.disabled) {
      fld.focus();
    }
  }
  return pass;
};

mBLAST.isEmpty = function (fldValue) {
  if (fldValue === null || fldValue === undefined || fldValue.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1") === '') {
    return true;
  }
  return false;
};

mBLAST.disableButtons = function (frmId) {
  var i, e, frm = document.getElementById(frmId), reSWFName = /^SWFUpload_([1-9])+$/;
  // Check page when disabling buttons not needed
  for (i = 0; i < frm.elements.length; i = i + 1) {
    e = frm.elements.item(i);
    if (e.tagName === "INPUT" && (e.type === "hidden" && e.value === "NoDisableAfterSubmit")) {
      return;
    }
  }

  for (i = 0; i < frm.elements.length; i = i + 1) {
    e = frm.elements.item(i);
    if (e.tagName === "INPUT" && (e.type === "submit" || e.type === "button")) {
      e.disabled = true;
      e.style.cursor = "wait";
      e.className = e.className + "_disabled";
    } else if (e.tagName === "OBJECT") {
      // Disable 'Browse' flash buttons
      if (reSWFName.test(e.id) && (window.SWFUpload)) {
        SWFUpload.instances[e.id].setButtonDisabled(true);
      }
    }
  }
};

mBLAST.sendMsgToAdmin = function () {
  var subject = document.getElementById('Subject').value, body = document.getElementById('Comments_Text').value, vRegExp = new RegExp("<\/?[^>]+(>|$)", "g");
  body = body.replace(vRegExp, '');

  mBLAST.AjaxRequest({
    url: '/cd/ws/widget/wgt_myaccount.asp?Action=ContactAdministrator&Subject=' + subject + '&Body=' + body + '&rnd=' + Math.random(),
    params: '',
    success: function (result, request) {},
    failure: function (result, request) {}
  });
};

mBLAST.proposeAdmin = function () {
  var curAdminName = document.getElementById('CurAdminName').value, curAdminEmail = document.getElementById('CurAdminEmail').value, adminName = document.getElementById('AdminName').value, adminEmail = document.getElementById('AdminEmail').value, proposeText = document.getElementById('ProposeText').value, vRegExp = new RegExp("<\/?[^>]+(>|$)", "g");
  proposeText = proposeText.replace(vRegExp, '');
	
  mBLAST.AjaxRequest({
    url: '/cd/ws/widget/wgt_myaccount.asp?Action=ProposeAdministrator&CurAdminName=' + curAdminName + '&CurAdminEmail=' + curAdminEmail + '&AdminName=' + adminName + '&AdminEmail=' + adminEmail + '&ProposeText=' + proposeText + '&rnd=' + Math.random(),
    params: '',
    success: function (result, request) {},
    failure: function (result, request) {}
  });
};

mBLAST.SetNoWinner = function (rowID) {
  var fld = document.getElementById('Q' + rowID + '_RATING');
  if (fld !== null) {
    fld.options[1].selected = true;
    mBLAST.ChangePreviousValue(rowID, "0");
    mBLAST.showMessageBox('Alert', 'You have selected not to override your other "winner" judging(s) and so the judging below reflects the prior entries before you tried to save this judging', 400, 150, 0, ['OK'], [''], '');
  }
};

mBLAST.ChangePreviousValue = function (rowID, newvalue) {
  var prevVal = null, fld = document.getElementById('Q' + rowID + '_RATING'), splittedVal = "";
  if (fld !== null) {
    if (fld.getAttributeNode("previousValue") !== 'undefined') {
      prevVal = fld.getAttributeNode("previousValue").nodeValue;
      if (prevVal !== null) {
        splittedVal = prevVal.split(",");
        if (splittedVal.length === 2) {
          fld.setAttribute("previousValue", splittedVal[0] + "," + newvalue);
        }
      }
    }
  }
};

mBLAST.parsePhoneNumber = function (value) {
  var phone = ['', '', '', ''], i = 0, j = value.indexOf(' (');
  if (j > 0) {
    phone[0] = value.substring(i, j);
    phone[0] = phone[0].replace('+', '');
    i = j + 2;
    j = value.indexOf(') ');
    if (j > 0) {
      phone[1] = value.substring(i, j);
      i = j + 2;
      j = value.indexOf(' ext. ');
      if (j > 0) {
        phone[2] = value.substring(i, j);
        phone[3] = value.substr(j + 6);
      }
      else {
        phone[2] = value.substr(i);
      }
    }
  }
  return phone;
};

mBLAST.setPhoneNumber = function (frmElt, fldId, value) {
  var phone = mBLAST.parsePhoneNumber(value), i;
  for (i = 0; i < frmElt.elements.length; i = i + 1) {
    switch (frmElt.elements[i].id) {
    case fldId:
      frmElt.elements[i].value = phone[0];
      break;

    case fldId + '_1':
      frmElt.elements[i].value = phone[1];
      break;

    case fldId + '_2':
      frmElt.elements[i].value = phone[2];
      break;

    case fldId + '_3':
      frmElt.elements[i].value = phone[3];
      break;
    }
  }
};

mBLAST.parseDateTime = function (value) {
  var datetime = ['', '', '', '', '', '', ''], valueDate = '', valueTime = '', dt = '', i, j, tmp;
  if (value === '') {
    return datetime;
  }

  if (value.indexOf('\\') < 0) {
    valueTime = value;
  } else {
    dt = value.split(' ');
    valueDate = dt[0];
    if (dt.length > 1 && dt[1].indexOf(':') > 0) {
      valueTime = dt[1];
    }
  }
  // parse date
  i = 0;
  j = valueDate.lastIndexOf('\\');
  if (j > 0) {
    // Year
    datetime[2] = valueDate.substr(j + 1);
    i = j - 1;
    j = value.lastIndexOf('\\', i);
    if (j > 0) {
      // Month and Day
      datetime[0] = valueDate.substring(0, j);
      datetime[1] = valueDate.substring(j + 1, i + 1);
    } else {
      // Month or Quater
      datetime[0] = valueDate.substring(0, i + 1);
    }
  }
  // parse time
  i = 0;
  j = valueTime.indexOf(':');
  if (j > 0) {
    // Hour
    datetime[3] = valueTime.subring(i, j);
    i = j + 1;
    j = value.lastIndexOf(' ', i);
    if (j > 0) {
      datetime[4] = valueTime.substring(i, j);
      i = j + 1;
      j = value.lastIndexOf(' ', i);
      if (j > 0) {
        datetime[5] = valueTime.substring(i, j);
        datetime[6] = valueTime.substr(j + 1);
      } else {
        tmp = valueTime.substr(i).toUpperCase();
        if (tmp === 'AM' || tmp === 'PM') {
          datetime[5] = tmp;
        } else {
          datetime[6] = tmp;
        }
      }
    } else {
      datetime[4] = valueTime.substr(i);
    }
  }
  return datetime;
};

mBLAST.setDateTime = function (frmElt, fldId, value) {
  var datetime = mBLAST.parseDateTime(value), i;
  for (i = 0; i < frmElt.elements.length; i = i + 1) {
    switch (frmElt.elements[i].id) {
    case fldId + '_1':
      frmElt.elements[i].value = datetime[0];
      break;

    case fldId + '_2':
      frmElt.elements[i].value = datetime[1];
      break;

    case fldId + '_3':
      frmElt.elements[i].value = datetime[2];
      break;

    case fldId + '_4':
      frmElt.elements[i].value = datetime[3];
      break;

    case fldId + '_5':
      frmElt.elements[i].value = datetime[4];
      break;

    case fldId + '_6':
      frmElt.elements[i].value = datetime[5];
      break;
    }
  }
};

mBLAST.setDate = function (frmElt, fldId, value) {
  var datetime = mBLAST.parseDateTime(value), i;
  for (i = 0; i < frmElt.elements.length; i = i + 1) {
    switch (frmElt.elements[i].id) {
    case fldId + '_1':
      frmElt.elements[i].value = datetime[0];
      break;

    case fldId + '_2':
      frmElt.elements[i].value = datetime[1];
      break;

    case fldId + '_3':
      frmElt.elements[i].value = datetime[2];
      break;
    }
  }
};

mBLAST.setTime = function (frmElt, fldId, value) {
  var datetime = mBLAST.parseDateTime(value), i;
  for (i = 0; i < frmElt.elements.length; i = i + 1) {
    switch (frmElt.elements[i].id) {

    case fldId + '_1':
      frmElt.elements[i].value = datetime[3];
      break;

    case fldId + '_2':
      frmElt.elements[i].value = datetime[4];
      break;

    case fldId + '_3':
      frmElt.elements[i].value = datetime[5];
      break;

    }
  }
};

mBLAST.validateNameLetterCase = function (nameText) {
  var arr = [], i;
  if (nameText !== '') {
    arr = nameText.split(" ");
    for (i = 0; i < arr.length; i = i + 1) {
      if ((arr[i] === arr[i].toLowerCase()) || (arr[i] === arr[i].toUpperCase()) || (arr[i] !== (arr[i].substr(0, 1) + arr[i].substr(1).toLowerCase()))) {
        return false;
      }
    }
  }
  return true;
};

mBLAST.validateCompanyNameOnClickYesScript = function (frmName) {
	if (typeof frmTimeout !== "undefined") {
		clearTimeout(frmTimeout);
	}
	if (validatefrm(document.getElementById(frmName))) {
		mBLAST.hideMessageBox();
		if (mBLAST.submitMsgBox !== undefined) {
			mBLAST.hideSubmitWindow();
		}
//this is temporary code. later need to use mBLAST.loadFormContent instead
    var pageUrl, formId = "id", param, form;
    form = document.getElementById(frmName);
    if (form[formId] === undefined) {
      pageUrl = document.getElementById(form).action;
    }
    else {
      pageUrl = document.getElementById(form[formId]).action;
    }
    Ext.get(document.body).mask(mBLAST.LoadingImage);
    window.location.href= pageUrl + '?Action=Next';
//    mBLAST.loadFormContent(document.getElementById(frmName), "Action=Next");
	}
};

mBLAST.validateCompanyNameOnClick = function (fldName, frmName) {
  var fl = document.getElementById(fldName);
  if (fl) {
    if (!mBLAST.validateNameLetterCase(fl.value)) {
      mBLAST.showCompanyNameValidationBox(fldName, 'jscrpt:mBLAST.validateCompanyNameOnClickYesScript(' + frmName + ');');
      return false;
    }
  }
  return true;
};

mBLAST.showCompanyNameValidationBox = function (elName, sScriptYes) {
  var el = document.getElementById(elName), sMsgText = "";
  mBLAST.hideMessageBox();
  if (el) {
    sMsgText = "<table cellspacing=0 cellpadding=0 border=0><tr><td colspan=2>This <b>" + el.value + "</b> field will be presented as part of your company's overall record. Generally Company Names are presented in Title Case, where the first letters of each word are capitalized. The Company Name as you entered it is not in this format. Are you sure this is the proper way you wish to display your Company Name?<br><br>";
    sMsgText = sMsgText + "</td></tr></table>";
    mBLAST.showMessageBox('Title case confirmation', sMsgText, 500, 200, 0, ['Yes', 'No'], [sScriptYes,  'jscrpt:mBLAST.jscriptElementFocus("' + elName + '");'], '');
  }
  return false;
};

mBLAST.showNameValidationBoxYesScript = function (elFName, elLName, sScriptYes) {
  var elL = document.getElementById(elLName);
  if (!mBLAST.validateNameLetterCase(elL.value)) {
    return mBLAST.showNameValidationBox(elLName, sScriptYes);
  } else {
    mBLAST[sScriptYes.substr(sScriptYes.indexOf("mBlast.") + 15)].apply(this);
  }
};

mBLAST.getEmailElement = function () {
	return document.getElementById('Email');
};

mBLAST.validateFLNamesYesScript = function () {
  mBLAST.hideMessageBox();
  mBLAST.isValidCheck =  mBLAST.validateEmail(mBLAST.getEmailElement());
  flNamesValidation();
};

mBLAST.showNameValidationBox = function (elName, sScriptYes) {
	var el = document.getElementById(elName), sMsgText = "";
	mBLAST.hideMessageBox();
	if (el) {
		sMsgText = '<table cellspacing=0 cellpadding=0 border=0><tr><td colspan=2>This <b>' + el.value + '</b> field will be presented as part of your overall record. Generally first and last names are presented as Title Case, where the first letter is capitalized. Are you sure this is the proper way to display your name?';
		sMsgText = sMsgText + '</td></tr></table>';
		mBLAST.showMessageBox('Title case confirmation', sMsgText, 500, 200, 0, ['Yes', 'No'], [sScriptYes, 'jscrpt:mBLAST.jscriptElementFocus(' + elName + ');'], '');
	}
	return false;
};

mBLAST.showMessageBox = function (title, content, width, height, frmId, buttonNames, buttonActions, frmNameField) {
  // Dynamic Button Creation
  var myArray = [], btnParam = "", frmElt = "", eltName = "", values = "", elt = "", i = 0, j = 0, l = 0;
  mBLAST.addButtonToArray = function (name, action, actionFormId) {
    myArray[myArray.length] = new Ext.Button({
      text: name,
      id: name,
      cls: 'buttonopen',
      listeners: {
        click: function () {
          if (action === '') {
            mBLAST.hideMessageBox();
          } else if (action.indexOf("jscrpt:") === 0) {
            mBLAST.jscriptCall(action);
          } else if (action.indexOf(":") > 0) {
            btnParam = action.split(':');
            if (btnParam.length === 2) {
              frmElt = document.forms[actionFormId];
              if (frmElt) {
                for (i = 0; i < frmElt.elements.length; i = i + 1) {
                  // Checkboxes
                  if (frmElt.elements[i].id === btnParam[0] + '_I1') {
                    eltName = btnParam[0] + '_I';
                    values = btnParam[1].split('|');
                    for (j = 0; j < frmElt.elements.length; j = j + 1) {
                      if (frmElt.elements[j].id.substr(0, eltName.length) === eltName) {
                        for (l = 0; l < values.length; l = l + 1) {
                          // set marks for checkboxes
                          if (frmElt.elements[j].value === values[l]) {
                            frmElt.elements[j].checked = true;
                          }
                        }
                      }
                    }
                  } else if (frmElt.elements[i].id === btnParam[0] || frmElt.elements[i].id === btnParam[0] + '_1') {
                    elt = frmElt.elements[i];
                    // Radio
                    if (elt.nodeName === 'INPUT' && elt.type === 'radio') {
                      if (elt.value === btnParam[1]) {
                        elt.checked = true;
                      }
                    } else {
                      // Phone number
                      if (document.getElementsByName(btnParam[0] + '_3').length > 0 && document.getElementsByName(btnParam[0]).length > 0) {
												mBLAST.setPhoneNumber(frmElt, btnParam[0], btnParam[1]);
                      } 
					  else {
                        // Dates
                        if (document.getElementsByName(btnParam[0] + '_6').length > 0) {
                          mBLAST.setDateTime(frmElt, btnParam[0], btnParam[1]);
                        } else if (document.getElementsByName(btnParam[0] + '_3').length > 0) {
                          if (document.getElementsByName(btnParam[0] + '_3')[0].nodeName === 'INPUT') {
                            mBLAST.setDate(frmElt, btnParam[0], btnParam[1]);
                          } 
						  else {
                            mBLAST.setTime(frmElt, btnParam[0], btnParam[1]);
                          }
                        } 
						else {
                          elt.value = btnParam[1];
                        }
                      }
                    }
                  }
                }
                mBLAST.hideMessageBox();
                mBLAST.disableButtons(frmElt.id);
                //mBLAST.loadFormContent(frmElt, '');
                frmElt.submit();
              }
            }
          }
        }
      }
    });
  };

  for (i = 0; i < buttonNames.length; i = i + 1) {
    mBLAST.addButtonToArray(buttonNames[i], buttonActions[i], frmId);
  }
	
  mBLAST.messageBox = new Ext.Window({
    title: title,
    width: width + 20,
		height: height + 20,
    items: [{
      labelStyle: 'padding:5px 5px 5px 5px;',
      xtype: 'label',
      id: 'ms_content',
      html: content
    }],
    buttons: myArray,
    buttonAlign: 'center',
    closable: true,
    draggable: false,
    modal: true,
    listeners: {
      close: function () {
        if (frmNameField !== '') {
          mBLAST.addCompanyPopUp_Choice1(frmNameField);
        } 
      }
    }
  });
	mBLAST.messageBox.show();
}; 

mBLAST.addCompanyPopUp_Choice1 = function (nameField) {
  var objSearchField = document.getElementById(nameField + 'search');
  mBLAST.hideMessageBox();
	if (objSearchField) {
		objSearchField.focus();
	}
};

mBLAST.hideMessageBox = function () {
  if (mBLAST.messageBox) {
    mBLAST.messageBox.hide();
  }
};
// function to override default HtmlEditor class
mBLAST.htmlEditorOverride = function () {
  Ext.override(Ext.form.HtmlEditor, {
    // private used internally
    createLink : function () {
      var url, doc, txt, html;
      url = prompt(this.createLinkText, this.defaultLinkValue);
      if (Ext.isIE) {       
        this.win.focus();
        doc = this.getDoc();
        txt = (doc.selection.createRange().text);
      }
      else if (Ext.isGecko || Ext.isOpera) {
        txt = this.win.getSelection();      
      }
      if (url && url !== 'http:/' + '/') {
        html = '<a href="' + url + '" target="_blank" >' + txt + '</a>';
        this.insertAtCursor(html);
      }
    },
    fixKeys : function () { // load time branching for fastest keydown performance
      if (Ext.isIE) {
        return function (e) {
          var k, doc, r, target;
          k = e.getKey();
          doc = this.getDoc();
          if (k === e.TAB)
          {
            e.stopEvent();
            r = doc.selection.createRange();
            if (r) 
            {
              r.collapse(true);
              r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;');
              this.deferFocus();
            }
          }
		  else if (k === e.ENTER)
		  {
            r = doc.selection.createRange();
            if (r) 
            {
              target = r.parentElement();
              if (!target || target.tagName.toLowerCase() !== 'li')
			  {
                //e.stopEvent();
                //r.pasteHTML('<br />');
                //r.collapse(false);
                //r.select();
              }
            }
          }
        };
      }
      else if (Ext.isOpera)
      {
        return function (e) {
          var k;
          k = e.getKey();
          if (k === e.TAB)
          {
            e.stopEvent();
            this.win.focus();
            this.execCmd('InsertHTML', '&nbsp;&nbsp;&nbsp;&nbsp;');
            this.deferFocus();
          }
        };
      }
	  else if (Ext.isWebKit)
      {
        return function (e) {
          var k;
          k = e.getKey();
          if (k === e.TAB)
          {
            e.stopEvent();
            this.win.focus();
            this.execCmd('InsertText', '\t');
            this.deferFocus();
          }
		  else if (k === e.ENTER)
          {
            e.stopEvent();
            this.execCmd('InsertHtml', '<br /><br />');
            this.deferFocus();
          }
        };
      }
    }(),
    createToolbar : function (editor) 
    {
      var items = [], tipsEnabled, fontSelectItem, tb, font;
      tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled();
      function btn(id, toggle, handler) {
        return {
          itemId : id,
          cls : 'x-btn-icon',
          iconCls: 'x-edit-' + id,
          enableToggle: toggle !== false,
          scope: editor,
          handler: handler || editor.relayBtnCmd,
          clickEvent: 'mousedown',
          tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined,
          overflowText: editor.buttonTips[id].title || undefined,
          tabIndex: -1
        };
      }
      if (this.enableFont && !Ext.isSafari2)
      {
        fontSelectItem = new Ext.Toolbar.Item({
          autoEl: {
            tag: 'select',
            cls: 'x-font-select',
            html: this.createFontOptions()
          }
        });
        items.push(
          fontSelectItem,
          '-'
        );
      }
      if (this.enableFormat) {
        items.push(
          btn('bold'),
          btn('italic'),
          btn('underline')
        );
      }

      if (this.enableFontSize) {
        items.push(
          '-',
          btn('increasefontsize', false, this.adjustFont),
          btn('decreasefontsize', false, this.adjustFont)
        );
      }

      if (this.enableColors) {
        items.push(
          '-', {
            itemId: 'forecolor',
            cls: 'x-btn-icon',
            iconCls: 'x-edit-forecolor',
            clickEvent: 'click',
            tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined,
            tabIndex: -1,
            menu: new Ext.menu.ColorMenu({
              allowReselect: true,
              focus: Ext.emptyFn,
              value: '000000',
              plain: true,
              listeners: {
                scope: this,
                select: function (cp, color) {
                  this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#' + color : color);
                  this.deferFocus();
                }
              },
              clickEvent: 'mousedown'
            })
          }, {
            itemId: 'backcolor',
            cls: 'x-btn-icon',
            iconCls: 'x-edit-backcolor',
            clickEvent: 'click',
            tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined,
            tabIndex: -1,
            menu : new Ext.menu.ColorMenu({
              focus: Ext.emptyFn,
              value: 'FFFFFF',
              plain: true,
              allowReselect: true,
              listeners: {
                scope: this,
                select: function (cp, color) {
                  if (Ext.isGecko) {
                    this.execCmd('useCSS', false);
                    this.execCmd('hilitecolor', color);
                    this.execCmd('useCSS', true);
                    this.deferFocus();
                  } else {
                    this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#' + color : color);
                    this.deferFocus();
                  }
                }
              },
              clickEvent: 'mousedown'
            })
          }
        );
      }
      if (this.enableAlignments) {
        items.push(
          '-',
          btn('justifyleft'),
          btn('justifycenter'),
          btn('justifyright')
        );
      }
      if (!Ext.isSafari2) {
        if (this.enableLinks) {
          items.push(
            '-',
            btn('createlink', false, this.createLink)
          );
        }

        if (this.enableLists) {
          items.push(
            '-',
            btn('insertorderedlist'),
            btn('insertunorderedlist')
          );
        }
        if (this.enableSourceEdit) {
          items.push(
            '-',
            btn('sourceedit', true, function (btn) {
              this.toggleSourceEdit(!this.sourceEditMode);
            })
          );
        }
      }

      // build the toolbar
      tb = new Ext.Toolbar({
        renderTo: this.wrap.dom.firstChild,
        items: items
      });

      if (fontSelectItem) {
        this.fontSelect = fontSelectItem.el;
        this.mon(this.fontSelect, 'change', function () {
          font = this.fontSelect.dom.value;
          this.relayCmd('fontname', font);
          this.deferFocus();
        }, this);
      }

      // stop form submits
      this.mon(tb.el, 'click', function (e) {
        e.preventDefault();
      });

      this.tb = tb;
      this.tb.doLayout();
    }
  });
};

mBLAST.htmlEditor = function (questionID, editorValue) {
  var objSpan, strTagName, editorConfig, delayObj, editorDiv;

  Ext.BLANK_IMAGE_URL = '/ext/resources/images/default/s.gif';
  Ext.QuickTips.init();
  mBLAST.htmlEditorOverride();
  delayObj = new Ext.util.DelayedTask(function () {
 
    objSpan = document.getElementById(questionID + 'HtmlEditor');
    strTagName = (objSpan !== null) ? objSpan.tagName.toLowerCase() : '';
    editorConfig = {
      renderTo: questionID + 'HtmlEditor',
      id: questionID,
      name: questionID,
      fieldLabel: 'Text - multiple lines (WYSIWYG)',
      width: 550,
      height: 150,
      allowBlank: false,
      enableLists: false,
      value : editorValue,
      helpText: 'This is html editor field.'
    };

    if ((objSpan !== null) && (strTagName === 'span')) {
      editorDiv = new Ext.form.HtmlEditor(editorConfig);
    }
  });
  delayObj.delay(500);
};

//Function to attach required field indicator and help icon with ext js form field labels
mBLAST.fieldLabelMarker = function() {
  if (mBLAST.isFieldMarked === undefined) {
    mBLAST.isFieldMarked = false;
  }
  if (!mBLAST.isFieldMarked) {
    Ext.apply(Ext.layout.FormLayout.prototype, {
      originalRenderItem: Ext.layout.FormLayout.prototype.renderItem,
      renderItem: function(c, position, target) {
        if (c && !c.rendered && c.isFormField && c.fieldLabel) {
          if (c.allowBlank === false) {
            if (c.helpText) {
              c.fieldLabel = c.fieldLabel + '<span class="required-field-indicator">*</span> <img onmouseover="javascript: mBLAST.showToolTip(\'' + c.fieldLabel + '\', \'' + c.helpText + '\');" src="/images/newui/help.gif" />';
            }
            else {
              c.fieldLabel = c.fieldLabel + '<span class="required-field-indicator">*</span>';
            }
          }
          else if (c.helpText) {
            c.fieldLabel = c.fieldLabel + '<img onmouseover="javascript: mBLAST.showToolTip(\'' + c.fieldLabel + '\', \'' + c.helpText + '\');" src="/images/newui/help.gif" />';
          }
        }
        this.originalRenderItem.apply(this, arguments);
      }
    });
    mBLAST.isFieldMarked = true;
  }
};

var tree, form, formLength, jsonNodeData, NavigationTreeMenu, NavigationWindow, jsonData, dataArr, NavigationForm, nodeItem, nodeID, cmbMenu, cmbBrand, BrandData, MenuData;


mBLAST.navigationTree = function () {

  if (document.getElementById('RootNavigationID').value > 0 && document.getElementById('RootNavigationText').value !== '') {
    mBLAST.RootVisible = true;
  }
  else {
    mBLAST.RootVisible = false;
  }

  mBLAST.NavigationTreeLoader = new mBLAST.JsonTreeLoader({
    dataUrl: mBLAST.HTTP + mBLAST.serverName + '/' + mBLAST.applicationName + '/' + mBLAST.handlerName + '/' + 'FetchNavigationsByRootNavigationID',
    method: 'post'
  });

  mBLAST.NavigationTreeLoader.on('beforeload', function (treeLoader, node) {
  }, this);
  mBLAST.nodeID = null;
  mBLAST.NavigationTreeMenu = new Ext.tree.TreePanel({
    id: 'NavigationTreeMenu',
    title: 'Tree Menu',
    split: true,
    width: 400,
    hight: 600,
    useArrows: true,
    autoScroll: true,
    animate: true,
    enableDD: true,
    containerScroll: true,
    border: true,
    rootVisible: mBLAST.RootVisible,
    bodyStyle: 'background-color:transparent',
    listeners: { 'render': function (tp) {
      tp.getSelectionModel().on('selectionchange', function (NavigationTreeMenu, node) {
        if (node !== null) {
          mBLAST.nodeID = node.id;
        }
      });
    }
    },
    stateful: true,
    stateEvents: ['click', 'contextmenu', 'hide', 'show', 'destroy', 'collapsenode', 'expandnode'],
    loader: mBLAST.NavigationTreeLoader,
    root: {
      nodeType: 'async',
      text: document.getElementById('RootNavigationText').value,
      draggable: false,
      id: document.getElementById('RootNavigationID').value
    },
    renderTo: 'NavigationTree',
    tbar: [{
        text: 'Add',
        iconCls: 'tree-editor-add',
        handler: function () {
          if (mBLAST.nodeID !== undefined && mBLAST.nodeID !== null && mBLAST.NavigationTreeMenu.selModel.selNode !== null) {
            var nWindow;
            if (!nWindow) {
              nWindow = new mBLAST.NavigationWindow({
                title: 'Menu Editor'
              });
            }
            nWindow.show(this);
            mBLAST.PopulateNavigationWindow(mBLAST.nodeID, 'Add');
          }
          else {
            Ext.Msg.minWidth = 200;
            Ext.Msg.alert('Select!', 'Please select a menu');
          }
        },
        scope: this
      }, {
        text: 'Modify',
        iconCls: 'tree-editor-edit',
        handler: function () {
          if (mBLAST.nodeID !== undefined && mBLAST.nodeID !== null && mBLAST.NavigationTreeMenu.selModel.selNode !== null) {
            var nWindow;
            if (!nWindow) {
              nWindow = new mBLAST.NavigationWindow({
                title: 'Menu Editor'
              });
            }
            nWindow.show(this);
            mBLAST.PopulateNavigationWindow(mBLAST.nodeID, 'Modify');
          }
          else {
            Ext.Msg.minWidth = 200;
            Ext.Msg.alert('Select!', 'Please select a menu');
          }
        },
        scope: this
      }, '->', {
        text: 'Delete',
        iconCls: 'tree-editor-delete',
        handler: function () {
          if (mBLAST.nodeID !== undefined && mBLAST.nodeID !== null && mBLAST.NavigationTreeMenu.selModel.selNode !== null) {
            mBLAST.deleteNavigation(mBLAST.nodeID);
          }
          else {
            Ext.Msg.minWidth = 200;
            Ext.Msg.alert('Select!', 'Please select a menu');
          }
        },
        scope: this
      }]
    });

  mBLAST.NavigationTreeMenu.render();
  mBLAST.NavigationTreeMenu.expandAll();

  Ext.QuickTips.init();


  if (document.getElementById('RootNavigationID').value < 0) {
    var win;
    if (!win) {
      win = new mBLAST.NavigationWindow({
        title: 'Menu Editor'
      });
    }
    win.show(this);
    document.getElementById('NavigationID').value = '0';
    document.getElementById('ParentID').value = '0';
    document.getElementById('Text').value = '';
    document.getElementById('URL').value = '';
    document.getElementById('IconClass').value = '';
    document.getElementById('Expanded').checked = false;
  }

};


mBLAST.NavigationWindow = Ext.extend(Ext.Window, {
  layout: 'fit',
  hight: 500,
  width: 400,
  closable: false,
  draggable: false,
  resizable: false,
  buttonAlign: 'center',
  closeAction: 'close',
  modal: true,

  initComponent: function () {
    mBLAST.BrandData = new Ext.data.SimpleStore({
      fields: ['BrandID', 'Description'],
      data: []
    });



    mBLAST.cmbBrand = new Ext.form.ComboBox({
      xtype: 'combo',
      fieldLabel: 'Brand Name',
      id: 'BrandID',
      name: 'bId',
      store: mBLAST.BrandData,
      mode: 'local',
      autoLoad: true,
      triggerAction: 'all',
      width: 250,
      emptyText: '--Select--',
      displayField: 'Description',
      valueField: 'BrandID',
      typeAhead: false,
      forceSelection: false,
      editable: false
    });

    mBLAST.MenuData = new Ext.data.SimpleStore({
      fields: ['MenuID', 'CategoryName'],
      data: []
    });



    mBLAST.cmbMenu = new Ext.form.ComboBox({
      xtype: 'combo',
      fieldLabel: 'Menu Name',
      id: 'MenuID',
      name: 'mId',
      store: mBLAST.MenuData,
      mode: 'local',
      autoLoad: true,
      triggerAction: 'all',
      width: 250,
      emptyText: '--Select--',
      displayField: 'CategoryName',
      valueField: 'MenuID',
      typeAhead: false,
      forceSelection: false,
      editable: false
    });
    mBLAST.NavigationWindow.superclass.initComponent.call(this);

    mBLAST.NavigationForm = new Ext.FormPanel({
      id: 'NavigationForm',
      bodyStyle: 'padding:5px 5px 0',
      border: true,
      width: 400,
      height: 250,
      buttonAlign: 'left',
      labelWidth: 100,
      items: [{
        fieldLabel: 'NavigationID',
		    name: 'nId',
		    id: 'NavigationID',
		    xtype: 'hidden'
		  },
        mBLAST.cmbBrand,
        mBLAST.cmbMenu,
		    {
		    fieldLabel: 'ParentID',
		    name: 'pId',
		    id: 'ParentID',
		    xtype: 'hidden'
		  },
		    {
		    fieldLabel: 'Text',
		    name: 'txt',
		    id: 'Text',
		    xtype: 'textfield',
		    width: 250,
		    allowBlank: false,
		    blankText: 'Text must be entered'
		  },
		    {
		    fieldLabel: 'URL',
		    name: 'urlLink',
		    id: 'URL',
		    width: 250,
		    xtype: 'textarea'
		  },
		    {
		    fieldLabel: 'IconClass',
		    name: 'iClass',
		    id: 'IconClass',
		    xtype: 'textfield',
		    width: 250
		  },
		    {
		    fieldLabel: 'Expanded',
		    name: 'exp',
		    id: 'Expanded',
		    xtype: 'checkbox'
		  }]
    });

    this.add(mBLAST.NavigationForm);

    this.saveButton = new Ext.Button({
      text: 'Save',
      iconCls: 'tree-editor-save',
      scope: this,
      minWidth: 75,
      handler: function () {
        Ext.Msg.minWidth = 200;
        if (mBLAST.cmbBrand.value <= 0 || !mBLAST.cmbBrand.value) {
          Ext.Msg.alert('Select!', 'Please select a Brand');
        }
        else if (mBLAST.cmbMenu.value <= 0 || !mBLAST.cmbMenu.value) {
          Ext.Msg.alert('Select!', 'Please select a Menu');
        }
        else if (document.getElementById('Text').value.length <= 0) {
          Ext.Msg.alert('Enter!', 'Please enter the text');
        }
        else {
          mBLAST.saveNavigation();
          this.close();
        }
      }
    });
    this.cancelButton = new Ext.Button({
      text: 'Cancel',
      iconCls: 'tree-editor-cancel',
      scope: this,
      minWidth: 75,
      handler: function () {
        this.close();
        if (document.getElementById('RootNavigationID').value < 0) {
          mBLAST.loadContent('innavigation/search.aspx');
        }

      }
    });
    this.addButton(this.saveButton);
    this.addButton(this.cancelButton);
    mBLAST.LoadMenu();
    mBLAST.LoadBrand();
  }
});



mBLAST.LoadBrand = function () {
  mBLAST.AjaxRequest({
    method: 'get',
    url: mBLAST.HTTP + mBLAST.serverName + '/' + mBLAST.applicationName + '/' + mBLAST.handlerName + '/' + 'FetchBrands',
    success: function (response, request) {
      var dataArr, jsonData, row, i;
      dataArr = [];
      jsonData = Ext.util.JSON.decode(response.responseText);
      row = {};
      for (i = 0; i < jsonData.length; i = i + 1) {
        row = Ext.util.JSON.decode(jsonData[i]);
        dataArr[dataArr.length] = [row.BrandID, row.Description];
      }
      mBLAST.BrandData.loadData(dataArr);
    },
    failure: function (response, request) {
      mBLAST.errorWindow(response, request);
      Ext.get(document.body).unmask();
    }
  });
};
mBLAST.LoadMenu = function () {
  mBLAST.AjaxRequest({
    method: 'get',
    url: mBLAST.HTTP + mBLAST.serverName + '/' + mBLAST.applicationName + '/' + mBLAST.handlerName + '/' + 'FetchHelpMenu',
    success: function (response, request) {
      var dataArr, jsonData, row, i;
      dataArr = [];
      jsonData = Ext.util.JSON.decode(response.responseText);
      row = {};
      for (i = 0; i < jsonData.length; i = i + 1) {
        row = Ext.util.JSON.decode(jsonData[i]);
        dataArr[dataArr.length] = [row.MenuID, row.CategoryName];
      }
      mBLAST.MenuData.loadData(dataArr);
    },
    failure: function (response, request) {
      mBLAST.errorWindow(response, request);
      Ext.get(document.body).unmask();
    }
  });
};

mBLAST.JsonTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
  requestData: function (node, callback) {
    if (this.fireEvent('beforeload', this, node, callback) !== false) {
      this.transId = Ext.Ajax.request({
        method: this.requestMethod,
        url: this.dataUrl,
        success: this.handleResponse,
        failure: this.handleFailure,
        scope: this,
        argument: { callback: callback, node: node },
        params: this.getParams(node),
        jsonData: { 'node': node.id }
      });
    }
    else {
      if (typeof callback === 'function') {
        callback();
      }
    }
  },
  processResponse: function (response, node, callback) {
    try {
      var json, arrDoubleDimention, arrSingleDimention, len, i, nodeItem;
      json = response.responseText;
      arrDoubleDimention = Ext.util.JSON.decode(json);
      arrDoubleDimention = arrDoubleDimention.d ? arrDoubleDimention.d : arrDoubleDimention;
      node.beginUpdate();
      for (i = 0, len = arrDoubleDimention.length; i < len; i = i + 1) {
        arrSingleDimention = Ext.util.JSON.decode(arrDoubleDimention[i]);
        nodeItem = this.createNode(arrSingleDimention);
        if (nodeItem) {
          node.appendChild(nodeItem);
        }
      }
      node.endUpdate();
      if (typeof callback === 'function') {
        callback(this, node);
      }
    }
    catch (e) {
      this.handleFailure(response);
    }
  }
});

mBLAST.PopulateNavigationWindow = function (node, Mode) {
  var json, form, arrDoubleDimention, arrSingleDimention;
  form = Ext.getCmp('NavigationForm');
  mBLAST.AjaxRequest({
    url: mBLAST.HTTP + mBLAST.serverName + '/' + mBLAST.applicationName + '/' + mBLAST.handlerName + '/' + 'FetchNavigationByNavigationID',
    method: 'post',
    params: { id: node },
    jsonData: this.jsonData || { 'node': node },
    success: function (response, request) {
      json = response.responseText;
      arrDoubleDimention = Ext.util.JSON.decode(json);
      arrDoubleDimention = arrDoubleDimention.d ? arrDoubleDimention.d : arrDoubleDimention;
      arrSingleDimention = Ext.util.JSON.decode(arrDoubleDimention[0]);
      if (Mode === 'Add') {
        if (document.getElementById('RootNavigationID').value > 0) {
          mBLAST.cmbBrand.setValue(arrSingleDimention.BrandID);
          mBLAST.cmbMenu.setValue(arrSingleDimention.MenuID);
        }
        document.getElementById('NavigationID').value = 0;
        document.getElementById('ParentID').value = arrSingleDimention.NavigationID;
        document.getElementById('Text').value = '';
        document.getElementById('URL').value = '';
        document.getElementById('IconClass').value = '';
        document.getElementById('Expanded').checked = false;
      }
      else {
        mBLAST.cmbBrand.setValue(arrSingleDimention.BrandID);
        mBLAST.cmbMenu.setValue(arrSingleDimention.MenuID);
        document.getElementById('NavigationID').value = arrSingleDimention.NavigationID;
        document.getElementById('ParentID').value = arrSingleDimention.ParentID;
        document.getElementById('Text').value = arrSingleDimention.Text;
        document.getElementById('URL').value = arrSingleDimention.URL;
        document.getElementById('IconClass').value = arrSingleDimention.IconClass;
        document.getElementById('Expanded').checked = arrSingleDimention.Expanded;
      }
      if (document.getElementById('ParentID').value === '0') {
        mBLAST.cmbMenu.disabled = false;
      }
      else {
        mBLAST.cmbMenu.disabled = true;
      }
    },
    failure: function (response, request) {
      mBLAST.errorWindow(response, request);
      Ext.get(document.body).unmask();
    }
  });
};

mBLAST.saveNavigation = function() {
  var parentID = -1, i, json, form, formLength, quote, arrDoubleDimention, arrSingleDimention, jsonNodeData;
  form = Ext.getCmp('NavigationForm');
  formLength = form.items.length;
  quote = new Array(6);
  for (i = 0; i < formLength; i = i + 1) {
    quote[i] = form.items.items[i].getValue();
    if (i == 3) {
      parentID = form.items.items[i].getValue();
    }
  }

  jsonNodeData = { 'NodeData': quote };
  mBLAST.AjaxRequest({
    url: mBLAST.HTTP + mBLAST.serverName + '/' + mBLAST.applicationName + '/' + mBLAST.handlerName + '/' + 'InsertNavigation',
    method: 'post',
    params: { 'NodeData': quote },
    jsonData: jsonNodeData,
    success: function(response, request) {
      var tree;
      json = response.responseText;
      arrDoubleDimention = Ext.util.JSON.decode(json);
      arrDoubleDimention = arrDoubleDimention.d ? arrDoubleDimention.d : arrDoubleDimention;
      arrSingleDimention = Ext.util.JSON.decode(arrDoubleDimention[0]);
      tree = window.top.Ext.getCmp('NavigationTreeMenu');
      if (parentID == 0) {
        mBLAST.loadContent('innavigation/navigationtree.aspx?RootNavigationId=' + arrSingleDimention.NavigationID + '&RootText=' + arrSingleDimention.Text);
      }
      else {
        tree.RootVisible = true;
        mBLAST.RootVisible = true;
        tree.root.reload();
        tree.render();
        tree.expandAll();
      }
    },
    failure: function(response, request) {
      mBLAST.errorWindow(response, request);
      Ext.get(document.body).unmask();
    }
  });
};

mBLAST.deleteNavigation = function (node) {
  Ext.Msg.minWidth = 400;
  Ext.Msg.confirm('Delete?', 'Do you want to delete?' + '<br><br>' + 'Note: ' + 'All the child menus will be deleted under this selected menu.', function (btn, text) {
    if (btn === 'yes') {
      mBLAST.AjaxRequest({
        url: mBLAST.HTTP + mBLAST.serverName + '/' + mBLAST.applicationName + '/' + mBLAST.handlerName + '/' + 'DeleteNavigation',
        method: 'post',
        params: { id: node },
        jsonData: this.jsonData || { 'node': node },
        success: function (response, request) {
          var tree;
          tree = window.top.Ext.getCmp('NavigationTreeMenu');
          if (document.getElementById('RootNavigationID').value === node) {
            mBLAST.loadContent('innavigation/search.aspx');
          }
          else {
            tree.RootVisible = true;
            mBLAST.RootVisible = true;
            tree.root.reload();
            tree.expandAll();
            tree.selModel.selNode = null;
          }
        },
        failure: function (response, request) {
          mBLAST.errorWindow(response, request);
          Ext.get(document.body).unmask();
        }
      });
    }
  });
};

//Function to include a list of javascript files to the page header
mBLAST.includeJavaScripts = function (fileList) {
  var i, regx, flag;
  if (mBLAST.loadedJsFile === undefined)
  {
    mBLAST.loadedJsFile = '';
  }
  for (i = 0; i < fileList.length; i = i + 1)
  {
    flag = false;
    regx = new RegExp(fileList[i], 'i');
    if (mBLAST.loadedJsFile === '')
    {
      mBLAST.loadedJsFile = fileList[i];
      flag = true;
    }
    else
    {
      if(!regx.test(mBLAST.loadedJsFile))
      {
        mBLAST.loadedJsFile = mBLAST.loadedJsFile + ', ' + fileList[i];
        flag = true;
      }
    }
    if (flag) 
    {
      mBLAST.loadJavascriptFile(fileList[i]);
    }
  }
}
