﻿var Locked = false;
var Lin = false;
var LinInProgress = false;
var isInError = false;
var OE = "O";
var messageCount = 0;
// screen toggled? false = default, true = content area is expanded
var isToggled = false;
    
// IE version booleans
var ISIE = false;
var ISIE8 = false;
var ISIE7 = false;
var ISIE6 = false;
var ISIE5 = false;

var mouseUp = true;

var baseURL = "/default.aspx";

// set the IE version boolean    
setIEversion(); 

  $(document).ready(function() { 
    
    $(document).mouseup(function(){ 
       mouseUp = true;    
    });
    
    $(document).mousedown(function(){ 
       mouseUp = false;   
    });
    
    $(".followMe").resize(function(){
      if (mouseUp) {
        fixGrid($(this).parent().attr('id'));
      }
    });
    
    if(Lin == false)
      {
        $(document).keypress(function(e) {
        if(e.keyCode == 13)
          {
            Login();
          }
        });
    }
    
    
    // bind the live events from 
    BindLiveEvents();
    
    // dialoge control
    HandleDialog(GetFeedback(), "", "")
    
    HandleGets();
    
    $(this).ajaxStart(function(){
      dd = '';
      requestStarted();
    });
    
    $(this).ajaxStop(function(){  
      requestFinished();
      handleJSON(dd, 1);   
      SetOverallStatus("Ready");
      doCustomResize();
    });
    
  });


function  HandleGets()
{
  if (!IsPostBackResult() && GetFeedback().indexOf("!",0) < 0)
  {
     MakeAjaxCalls(GetFeedback());
  }
  return false;
}

function requestStarted() 
{
   //$('body').css('cursor', 'wait');
  //clean security alerts
  //document.getElementById("ajaxSecurity").innerHTML = '';
  ticker = setTimeout("postTicker()", tickerLength);
  return false;
}

function isIE() {
var browser=navigator.appName;
if (browser == "Microsoft Internet Explorer")
  {
  return true;
  }
else
  {
  return false;
  }
}

function requestFinished() 
{   
    Locked = false;
    //$('body').css('cursor', 'default');
    $("#tickerWindowContainer").hide();
    $("#statusMessages").html("&nbsp;");    
    clearTimeout(ticker);
    ticker = '';
    ticker = null;
    //postTicker();
  return false;
}

//#### DIALOG FUNCTIONS

function HandleDialog(d, inFpid, inFvid)
{
//   if (d.indexOf("!",0) > -1 || d.indexOf("~",0) > -1) 
//   {
//     Dialogue(inFpid, inFvid);
//   } 
   
   if (d.indexOf("!",0) > -1) 
   {
    DialogOpen = true;
    openDialog("dialog", "", "", "", "", "welcome", 500, 335, 0, 0, 0, 0, true, true, true, "login");
   } 
   
   return false;
}

//function cleanDialoge() {
//    try {
//         //treeOther.destroy();
//         //treeOther = null;
//         $("#aWindowInner ul").unbind();
//         $("#aWindowInner ul li").unbind();
//         $("#aWindowInner ul li a").unbind();
//     }
//     catch (err) {
//     
//     }
//     document.getElementById("aWindowInner").innerHTML = '';
//}

//function Dialogue(inFpid, inFvid)
//{
//  if (!DialogOpen) {
//    Locked = false;
//    toggleDialoge(true);
//  }
//  else {
//    //document.getElementById("aWindowInner").innerHTML = '';
//  }
//  SetOverallStatus("Req");
//  AjaxLoad("#aWindowInner","/parts/dialogs.aspx?fpid=" + inFpid + "&fvid=" + inFvid,"/js/controls/controls.Dialogs.js","loading dialoge","",false);
//  return false;
//}

//function DialogCustom(UserControl, jsFile)
//{
//  toggleDialoge(true);
//  SetOverallStatus("Req");
//  AjaxLoad("#aWindowInner","/parts/dialogs.aspx?uc=" + UserControl,jsFile,"","",false);
//}


var DialogOpen = false;
//function toggleDialoge(inShow)
//{
// if (inShow && !DialogOpen)
// {$("#windowContainer").show();
//  $("#darkSide").show();
//  DialogOpen= true;
//  Locked = false;
// } else
// {
//  $("#windowContainer").hide();
//  $("#darkSide").hide();
//  DialogOpen= false;
// }
// return false;
//}

function IsPostBackResult()
{
if (GetFeedback().indexOf("POST",0) > -1)
 return true;
 else
 return false;
}

function IsLoggedOut()
{
  if (GetFeedback().indexOf("!",0) > -1) {
    return true;
  }
  if (GetFeedback().indexOf("LOGINFAIL",0) > -1) {
   return true;
  }
  return false;
}

var _Feedback = "";
function GetFeedback()
{
  if (!_Feedback)
  {
    _Feedback = $("#hf")[0].innerHTML;
  }
  return _Feedback;
}

function SetFeedback(Feedback)
{
  _Feedback = Feedback;
  $("#hf")[0].innerHTML = Feedback;
}


var ticker;
var tickerFired = false;
var tickerLength = 1500;


function postTicker() {
  if (Locked)  {
    $("#tickerWindowContainer").show();
    setTimeout("postTicker()", 1000);
  }
  else {
    $("#tickerWindowContainer").hide();
  }
  return false;
}

//jQuery.fn.GTunBind = function() {
//  //unBindElements("#" + $(this).attr('id'));
//  purge(this);
//  
//};

//jQuery.fn.GTempty = function() {
//	this.empty();
//};

//jQuery.fn.GTpopulate = function(inhtml) {
//      this.html(inhtml);
//};

//jQuery.fn.GTbind = function() {
//   bindElements("#" + $(this).attr('id'));
//};



function MakeAjaxCalls(d, inFpid, inFvid)
{

 // clear any non updating alerts
 $("#ajaxAlertsPerm").empty();
 
 failLogin(d);
 
 SetOverallStatus("Resp");
 LInf(d);
 lWaL(d);
 lWa(d);
 lWaR(d)
 lAc(d);
 lMo(d);
 lMinf(d);
 //TABS
lTaL(d);
lTa(d);
lTaR(d);
lCu(d);
lAlerts(d, '');
// cultures
lc(d);
// LoadAPIScript();

if (IsLoggedOut()) {
   HandleDialog(d, "", "");
}

}

function AjaxLoad(inElementIdentifier,inAspx,inLoadScript,inStatusMessageStart,inStatusMessageEnd,inDoAdminPostback)
{
 var html;
 //inAspx = "/ajaxTest.aspx"
 $("#statusMessages").html("loading: " + inAspx)
 var elm = $(inElementIdentifier);
 if (elm.length > 0) {
  
  unBindElements(inElementIdentifier);
  //purge(elm[0]);
  if (inStatusMessageStart) $("#statusMessages").text(inStatusMessageStart);
	  $.ajax({
    url: inAspx,
    async: true,
    dataType: "html",
    success: function(html){
      //if (inElementIdentifier == "#ajaxSecurity") {
       // elm.append(html);
      //}
      //else {
        elm.contents().remove();
        //document.getElementById(inElementIdentifier.replace('#','')).innerHTML = '';
        elm.append(html);     
      //}
      bindElements(inElementIdentifier);
      if (html.indexOf('<div class="grid">') > -1) {
         fixGrid(inElementIdentifier.replace('#',''));
         var buttonRowHeights = 48
         var resizeRowHeight = 16
         $("#dialog .trackDialog").height($("#dialog").height() - buttonRowHeights - resizeRowHeight);
         if ($("#dialog .trackDialog .gridScroll").length > 0) {
             if ($("#dialog .gridFooter").length > 0) {
                buttonRowHeights = buttonRowHeights + $("#dialog .gridFooter").height();
             }
            fixGrid('dialog');
            $("#dialog .trackDialog .gridScroll").height($("#dialog").height() - buttonRowHeights - resizeRowHeight - 120);
         }
      }
     
      elm = null;
      html = '';
      if (inStatusMessageEnd) $("#statusMessages").text(inStatusMessageEnd);
      if (inDoAdminPostback) {
        PostIt();
      }
    }
	});
	$("#statusMessages").html("loaded: " + inAspx)
  }
 return true;
}



function AjaxLoadWithParams(inElementIdentifier,inAspx,inLoadScript,inStatusMessageStart,inStatusMessageEnd,inDoAdminPostback)
{
 //requestStarted();
 var qs = $('#av2form').formSerialize(); 
 if (inStatusMessageStart) $("#statusMessages").text(inStatusMessageStart);
  $(inElementIdentifier).load(inAspx,qs,
  function()
   {
     if (inLoadScript) $.getScript(inLoadScript, "");
     if (inStatusMessageEnd) $("#statusMessages").text(inStatusMessageEnd);
     if (inDoAdminPostback) {
      PostIt();
      }
   });
   return false;
}



function AjaxPost(inElementIdentifier,inAspx,inLoadScript,inStatusMessageStart,inStatusMessageEnd,inDoAdminPostback)
{

 if (inStatusMessageStart) $("#statusMessages").text(inStatusMessageStart);
 $.post(inAspx,"", function(html)
  {
      unBindElements(inElementIdentifier);
      if (inLoadScript) $.getScript(inLoadScript, "");
      ReplaceElementContent(inElementIdentifier,html);
      bindElements(inElementIdentifier);
      if (inStatusMessageEnd) $("#statusMessages").text(inStatusMessageEnd);
      if (inDoAdminPostback) {
      PostIt();
      }
  },"html"); 
  return false;
}

function cleanUpDropDowns() {
   // $("ul.exp").hide();
   // $("li.open").removeClass('open');
}

function DoIt(inCode,inPID,inVID, inControlID, inCommand, inForceAssetPointerID, inForceAssetVersionID)
{

if (!Locked)
 {
 
    
 
 //clearAlerts();
   CollapseOpen();
   Locked = true;
   //cleanUpDropDowns();
   if(inCode == "LOGOUT")
   {
        Lin = false;
        PostIt(inCode,inPID,inVID,inControlID,inCommand, "",inForceAssetPointerID,inForceAssetVersionID);
        return false;
   }
   
   if (inCode == "CONT") {
      // this is acontols, check its not a dialog
      
        $.ajax({
           type: "POST",
           url: "/parts/ajaxActionMethod.aspx",
           data: "pid=" + inControlID,
           dataType: "json",
           success: function(d){ 
             inID = d.action[0].inID;
             dialogID =  d.action[0].dialogID;
             actionID =  d.action[0].actionID;
             title =  d.action[0].title;
             width =  d.action[0].width;
             height =  d.action[0].height;
             maxWidth =  d.action[0].maxWidth;
             maxHeight =  d.action[0].maxHeight;
             minWidth =  d.action[0].minWidth;
             minHeight =  d.action[0].minHeight;
             if (d.action[0].modal == "true") {
              modal = true;
             }
             else {
              modal = false;
             }
             if (d.action[0].draggable == "true") {
              draggable = true;
             }
             else {
              draggable = false;
             }
             if (d.action[0].canResize == "true") {
              canResize = true;
             }
             else {
              canResize = false;
             }
             dialogClass =  d.action[0].dialogClass;
             
             openDialog(inID, dialogID, actionID, inForceAssetPointerID, inForceAssetVersionID, title, width, height, maxWidth, maxHeight, minWidth, minHeight, modal, draggable, canResize, dialogClass);
	         },
           error: function(){ 
              PostIt(inCode,inPID,inVID,inControlID,inCommand, "",inForceAssetPointerID,inForceAssetVersionID);
           } 
         });
   }
   else {
      PostIt(inCode,inPID,inVID,inControlID,inCommand, "",inForceAssetPointerID,inForceAssetVersionID);
   }
   
   
 } else {
 alert("Please wait until the request is complete");
 //if system has marked as ready unlock it incase we havent had a proper unlock (MW 17.10.2009)
 if ($("#overallStatus").text = "ready")
   {
   Locked = false;
   }
 }
 return true;
}

function toolTipHide(Object)
 {
 $(Object).hide();
 return false;
 }
 
function TreeClick(inPID)
{
  DoIt("TREE",inPID,"","","","","");
  return false;
}

function NavigationClick(inPID)
{
   DoIt("GO",inPID,"","","","","");
   return false;
}

//function UpdateJSControls() {
//    if ($("#workAreaUpdate #txt_Content").length > 0) {
//        UpdateEditor();
//    } 
//    return false;
//}

var dd;
function PostIt(inCode,inPID,inVID, inControlID, inCommand, onSuccess,inForceAssetPointerID,inForceAssetVersionID)
{


  if ((inControlID == '' || inControlID == null ) && inCode != "CANCEL") {
    // this is not a save (or any other action)
      if ($("#checker").text() == "true") {
          input_box=confirm("you will lose any changes you have made");
          if (input_box==true)
          { 
            $("#checker").text("false");
            // Output when OK is clicked
          }

          else
          {
          // Output when Cancel is clicked
            //Locked = false;
            return false;
          }
    }
  }




  $(".processMessages").empty();
  $("#ajaxAlertsPerRequest").remove();
  updateMessageCount(0);
  

  
  var qs;
  
  //UpdateJSControls();
  
  qs = $('#av2form').formSerialize();
  
  if (inCode == "LOGIN") {
     qs = qs + "&edtUserName=" + $("#edtUserName").val() + "&edtPassword=" + $("#edtPassword").val();
  }
  

  if ($(".anInnovaEditor").length > 0) {
    // at least one mce editor found
    $(".anInnovaEditor").each(
      function(){
        try {
        // loop through each one, extracting its html and adding it to the qs
        // as they will not be serialized as they have no name attr
        var theID = $(this).attr('id').replace("ed_", "");
        theID = "idContentoEdit_Center$" + theID;
        var innovaContent = getEditorContents(theID);
        var encodedContent = encodeContent(innovaContent);
        qs += "&txt_Content=" + encodedContent;
        theID = "";
        mceContent = "";
        encodedContent = "";
        }
        catch (e) {
          alert(e);
        }
      }
    );
  }
  // 
    
    if ($(".aPlanscapeColourSelector").length > 0) {

//      var valArray = $('input.PlanscapeColourTick:checkbox').serializeArray(); 
//      var len = valArray.length;
//      var Aspx = "/parts/_AjaxPostBack.aspx";
//      var ClrPointerStr = "";
//      
//      jQuery.each(valArray, function(i, field){
//        if (ClrPointerStr.length > 0) {
//          ClrPointerStr = ClrPointerStr + ",";
//        }
//        ClrPointerStr = ClrPointerStr + field.id;
//      });
//      
//      var valArray = $('input.PlanscapeColourTick:checkbox').serializeArray(); 
//      var len = valArray.length;
      var Aspx = "/parts/_AjaxPostBack.aspx";
      var ClrPointerStr = "";
      var IsEdit = false;
      
      jQuery.each($('input.PlanscapeColourTick:checkbox'), function(i, field){
      if (field.value != "" && field.checked) {
        if (ClrPointerStr.length > 0) {
          ClrPointerStr = ClrPointerStr + ",";
        }
        ClrPointerStr = ClrPointerStr + field.value;
        }
        IsEdit = true;
      });
      
           
      var qrs = "cod=SavePlanscapeColours&ColourIDs=" + ClrPointerStr;
  
  if (IsEdit == true)
  {
      $.post(
        Aspx, qrs, 
        function(d) 
          {
             if (d != "") alert(d);
          }
      )
      }
   }    







  if ($(".anMCE").length > 0) {
    // at least one mce editor found
    $(".anMCE").each(
      function(){
        try {
        // loop through each one, extracting its html and adding it to the qs
        // as they will not be serialized as they have no name attr
        var theID = $(this).attr('id');
        var mceContent = tinyMCE.get(theID).getContent()
        var encodedContent = encodeContent(mceContent);
        qs += "&" + theID + "=" + encodedContent;
        theID = "";
        mceContent = "";
        encodedContent = "";
        }
        catch (e) {
        
        }
      }
    );
  } 
  
  qs += "&pid=" + qsv(inPID) + "&vid=" + qsv(inVID) + "&cid=" + qsv(inControlID) + "&cod=" + qsv(inCode) + "&cmd=" + qsv(inCommand) + "&rezw=" + screen.width + "&rezh=" + screen.width;
  
//  if ($("#isMCE").val() == "true") {
//    var postedHTML = $('#txt_Content').html();
//    var qs = $('#av2form').formSerialize();
//    qs += "&txt_Content=" + encodeContent(postedHTML) + "&pid=" + qsv(inPID) + "&vid=" + qsv(inVID) + "&cid=" + qsv(inControlID) + "&cod=" + qsv(inCode) + "&cmd=" + qsv(inCommand) + "&rezw=" + screen.width + "&rezh=" + screen.width;
//  }
//  else {
//    
//    var qs = $('#av2form').formSerialize();
//    qs += "&pid=" + qsv(inPID) + "&vid=" + qsv(inVID) + "&cid=" + qsv(inControlID) + "&cod=" + qsv(inCode) + "&cmd=" + qsv(inCommand) + "&rezw=" + screen.width + "&rezh=" + screen.width;  
//  }
  
  SetOverallStatus("Req");
  $.ajax({
   type: "POST",
   url: baseURL,
   data: qs,
   dataType: "json",
   success: function(d){
    //$(".GT").remove();
    //$(".jGrowl-closer").remove();
    $("#alertIDsPerRequestStore").empty();
    var i = 0;
    var ajaxReponse = d.events[i].message;
    SetFeedback(ajaxReponse);
    MakeAjaxCalls(ajaxReponse, inForceAssetPointerID, inForceAssetVersionID);
    dd = d;
    d = '';
    qs = '';
    if (!onSuccess == "") {
      setTimeout(onSuccess, 1);
    }
    if(inCode == "LOGIN" && ajaxReponse != "LOGINFAIL")
    {
        //cleanDialoge();
        Lin = true;
    }
    
   }
 });
 //ajaxAlerts();
 //Locked = false;
 }

  function encodeContent(inStr) {
  if (inStr != null){
    //Variable that contains special characters.
    var strSample = inStr;
    //Trim the string varibale.
    strSample = strSample.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
    //Encode the string variable that contains special characters.
    strSample = encodeURIComponent(strSample);
    //Encode characters that are not covered in encodeURIComponent function.
    var encodedCharacters = new Array('~', '!', '*', '(', ')', '\'');
    var decodedCharacters = new Array('%7E', '%21', '%2A', '%28', '%29', '%60');
    for(var i=0; i<encodedCharacters.length; i++)
    {
      strSample = strSample.replace(encodedCharacters[i], decodedCharacters[i]);
    }
    return strSample;
    }
    return "";
  }


  var saveDraftInterval;

  function autoSaveTrigger() {
    //UpdateJSControls();
    var qs = $('#av2form').formSerialize();
    qs += "&pid=&vid=&cid=673de9db917f42c593898f9a6dbd5ce7&cod=CONT&cmd=";
    SetOverallStatus("Req");
    $.ajax({
     type: "POST",
     url: baseURL,
     data: qs,
     dataType: "json",
     success: function(d){
        var curDateTime = new Date()
        var curHour = curDateTime.getHours()
        var curMin = curDateTime.getMinutes()
        var curSec = curDateTime.getSeconds()
        var curTime = 
        ((curHour < 10) ? "0" : "") + curHour + ":" 
        + ((curMin < 10) ? "0" : "") + curMin + ":" 
        + ((curSec < 10) ? "0" : "") + curSec 
        messageCount = messageCount + 1;
        $("li#UImessagesCount").text((messageCount) + " UI messages");
        $("ul#UImessages").append("<li>saved draft: " + curTime + "</li>");
        //used to set the timer here again - but using set interval
        }
   });
   Locked = false;  
   return false;
  }
     
var asTimer;
function autoSave() {
 if (!asTimer)
 {
   if (!IsLoggedOut() && !Locked) {
     asTimer = setInterval("autoSaveTrigger()", saveDraftInterval);
   }
   }
 }


  function eventTrigger(inDestination, inAlertControl, inMessage, inImage, inQS) {
  if (!Locked)
    {
      $("#ajaxAlertsPerRequest").remove();
      $("#alertsManager").append('<div id="ajaxAlertsPerRequest" class="innerRow"></div>');
      AjaxLoad(inDestination, "/parts/ajaxAlertsPerRequest.aspx?qs=" + inQS +"&passAlertControl=" + inAlertControl + "&inMessage=" + inMessage + "&inImage=" + inImage,"","loading alerts...","alerts ok",false);
    }
  }


  function handleJSONalerts(d, i) 
  {
    if (IsLoggedOut()) 
    {
      return false;
    }
    if(d)
    {
     var ajaxReponse = d.alerts[i];
      if (ajaxReponse) {
        // message types
        var isSticky = false
        switch (d.alerts[i].alert) {
          case "STICKY":
            isSticky = true;
          break;
        }
        injectAlert(isSticky, d.alerts[i].header, d.alerts[i].message, d.alerts[i].ID, d.alerts[i].UPR, d.alerts[i].UPS)
        handleJSONalerts(d, i + 1)
      }
    }
  }
  
  function injectAlert(isSticky, inHeader, inMessage, ID, UPR, UPS) {
  
        if (UPR == "true") {
          if ($("#alertIDsPerRequestStore").text().indexOf(ID) > -1) {
            return false;
          }
        }

        if (UPS == "true") {
          if ($("#alertIDsPerSessionStore").text().indexOf(ID) > -1) {
            return false;
          }     
        }      

				$("#alertsContainer").jGrowl(inMessage, { 
					header: inHeader,
					theme: 'GT',
					sticky: isSticky,
					speed:  'slow',
//					beforeOpen: function(e,m,o) {
//						//console.log("I am going to be opened!", this);
//					},
					open: function(e,m,o) {
						//console.log("I have been opened!", this);
						if (UPR == "true") {
						  $("#alertIDsPerRequestStore").append(ID + ",");
						}
						if (UPS == "true") {
						  $("#alertIDsPerSessionStore").append(ID + ",");
						}
					}
//					beforeClose: function(e,m,o) {
//						//console.log("I am going to be closed!", this);
//					},
//					close: function(e,m,o) {
//						//console.log("I have been closed!", this);
//						
//					}
					
					
				});
  }
    


  function handleJSON(d, i) {
  if (IsLoggedOut()) 
  {
    return false;
  }
  if(d)
  {
    var ajaxReponse = d.events[i];
    if (ajaxReponse) {
      // message types
      switch (d.events[i].event) {
        case "SETCULTURE":
          if (d.events[i].message == "FAIL") {
             //trigger dialog
             //Cntrl("7ef0896814174f6a82857a9a966b7c22");
              eventTrigger("#ajaxAlertsPerRequest", "cultureFailAlert.ascx", "", "", "");
          }
          break;
         case "UIMESSAGE":
          //if (messageCount = 0) {
          //  $(".inlineAlerts").empty();
          //}
          if (messageCount < 100) {
            $(".processMessages").append("<div id=\"aMessage_" + messageCount + "\" class=\"aMessage\">" + d.events[i].message) + "</div>"; 
            setTimeout("procesMessageAdd('aMessage_" + messageCount + "')", messageCount * 200);
            setTimeout("procesMessageRemove('aMessage_" + messageCount + "')", 5000 + (messageCount * 300));
            updateMessageCount(1);
          }
          break;
      case "SEL_NODE":
          //has the selected asset PID
          setTreeNodeSelected(d.events[i].message);
          break;     
         case "EXCEPTION":
          //if (messageCount = 0) {
          //  $(".inlineAlerts").empty();
          //}
          $(".processMessages").append("<div id=\"aMessage_" + messageCount + "\" class=\"aMessage Exception\">" + d.events[i].message) + "</div>"; 
          setTimeout("procesMessageAdd('aMessage_" + messageCount + "')", messageCount * 200);
          //setTimeout("procesMessageRemove('aMessage_" + messageCount + "')", 5000 + (messageCount * 300));
          updateMessageCount(1);
          //$("ul#UImessages").append("<li>" + d.events[i].message + "</li>");
         
          break;          
         //case "SECURITYMESSAGE":  
            //eventTrigger("#ajaxSecurity", "securityAlert.ascx", d.events[i].message, "info_24.png", ""); 
          //break;
         case "CURCULTURE":
          $("span#currCulture").text(d.events[i].message);
          break;
         case "DRAFTBESTVERSION":
         // if (d.events[i].message == "FALSE") {
            //eventTrigger("draftNotBestVersionAlert.ascx");
         // }
//       case "ALERT":
           // eventTrigger(d.events[i].message, "", "info_24.png");
          break;
         case "LOGIN":
          if (d.events[i].message == "FAILED") {
            //Locked = false;
          }
          break;
         case "AUTOSAVE":
           if (d.events[i].message != "") {
            saveDraftInterval = d.events[i].message;
            autoSave();
          }   
          break;
      }
      // check for more messages
      handleJSON(d, i + 1)
    }
    else {
     // alert("no more messages");
      //$("li#UImessagesCount").text(messageCount + " UI messages");
      return false;
    }
    return false;
    }
  return false;
  }

  function setTreeNodeSelected(nodeID) {
      try {
          $("ul li a.clicked").removeClass('clicked');
       $("#Lid_" + nodeID + " a:first").addClass('clicked');
       //$("#" + nodeID)[0].children[0].className = "clicked";
    } catch(ex) {}
   }

  function procesMessageAdd(inID) {
    if ($("#" + inID).length > 0) {
      $("#" + inID).fadeIn(500);
    }
  }

  function procesMessageRemove(inID) {
    if (messageCount > 0) {
      if ($("#" + inID).length > 0) {
        $("#" + inID).fadeOut(750);
        updateMessageCount(-1);
      }
   }
  }

  function updateMessageCount(inqty) {
    if (inqty == 0) {
      messageCount = 0;
    }
    else {
      messageCount = messageCount + inqty
    }
    if (messageCount < 0) {
      messageCount = 0;
    }
    $("#ajaxMessagesPerRequest .modHeader span").empty();
    $("#ajaxMessagesPerRequest .modHeader span").append("(" + messageCount + ")");
  }

  function PostOnly(inCode,inQuerystring)
  {
   $.post('/parts/_AJAXPostback.aspx?cod=' + inCode + "&" + inQuerystring);
   return false;
  }

function qsv(inStr)
{
 if (inStr)
  return inStr;
  return ""; 
}

function LoadAPIScript()
{
 //$.getScript("/js/api/gta.API-1.0.js", "");

}

function ReplaceElementContent(inElementIdentifier, inContent)
{

  $(inElementIdentifier).empty();
  $(inElementIdentifier).append(inContent);
  return false;
}

function FocusElement(inElementIdentifier)
{
// if ($(inElementIdentifier)[0])
// {
//  $(inElementIdentifier)[0].focus();
// }
}

//function lDLog(d, inFpid, inFvid)//TREE
//{
// if (d.indexOf("LOGINFAIL",0) > -1) {
//  return false;
// }
// //Lin = true;
// if (d.indexOf("!",0) > -1)Dialogue(inFpid, inFvid) ;
// else
// {
// if (d.indexOf("~",0) > -1)Dialogue(inFpid, inFvid) ;
// else
// {
//  if (d.indexOf("#",0) < 0)
//   toggleDialoge(false);
// }
// }
// return false;
//}


function failLogin(d) {
  if (d.indexOf("LOGINFAIL",0) > -1) {
   $("#loginDlgHeader").empty();
   $("#loginDlgHeader").append("login failed, please check your username and password...");
   $("#edtPassword").val('');
  }
  else {
    if (DialogOpen) {
      closeUIdialog('dialog');
    }
  }
}

function LInf(d)//Info Area
{
if (IsLoggedOut()) 
{
$("#infoTxt").empty();
return false;
}
if (d.indexOf("I",0) > -1) 
AjaxLoad("#infoTxt", "/parts/info.aspx","","loading info...","info ok",false);
return false;
}

function pausecomp(millis) 
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); } 
while(curDate-date < millis);
} 

function bindElements(inElementIdentifier)
{

//    $(inElementIdentifier + " .followMe").resize(function(){
//      if (mouseUp) {
//        fixGrid($(this).parent().attr('id'));
//      }
//    });

  if (inElementIdentifier == "#ajaxAlertsInline") {
    //doCustomResize();
  }

  if (inElementIdentifier == "#actionList") {
   $('ul.actionsList ul.exp li:first-child').addClass("first");
   $('ul.actionsList ul.exp li:last-child').addClass("last");
  }
  if (inElementIdentifier == "#historyList") {
    $('ul.historyList ul.exp ul.listitem li:first-child').addClass("first");
    $('ul.historyList ul.exp ul.listitem li:last-child').addClass("last");
  }
  
  if ($(inElementIdentifier + " .datepicker").length > 0) {
       $(inElementIdentifier + ' .datepicker').datePicker(
			    {
				    showTime:false
			    }
	    );
	  }
  
  if ($(inElementIdentifier + " .datetimepicker").length > 0) {
       $(inElementIdentifier + ' .datetimepicker').datePicker(
			    {
				    showTime:true
			    }
	    );
	  }

  
  if (inElementIdentifier == "#workAreaUpdate") {
    // do resizing
    //doCustomResize();
  
    // crm
    ToolTipMagic($("div.CRM tr.jt"));
  
    if ($("#workAreaUpdate div.codeEditor textarea").length > 0) {
        LoadCodeEdit("#workAreaUpdate div.codeEditor textarea");
    }
//    if ($("#workAreaUpdate .datepicker").length > 0) {
//      $('#workAreaUpdate .datepicker').datePicker(
//			    {
//				    showTime:false
//			    }
//	    );
//	  }
//	  if ($("#workAreaUpdate .datetimepicker").length > 0) {
//		  $('#workAreaUpdate .datetimepicker').datePicker(
//				  {
//					  showTime:true
//				  }
//		  );
//	  }  
  }
  
  
  if (inElementIdentifier == "#dialog") {
    setInnerDialogHeights("dialog");
  }
  
 
  
//  if (inElementIdentifier == "#aWindowInner") {
//  
//    $('#aWindow').jqDrag('#draghandle');
//  
//    if ($("#aWindowInner .datepicker").length > 0) {
//      $('#aWindowInner .datepicker').datePicker(
//			    {
//				    showTime:false
//			    }
//	    );
//	  }
//	  if ($("#aWindowInner .datetimepicker").length > 0) {
//		  $('#aWindowInner .datetimepicker').datePicker(
//				  {
//					  showTime:true
//				  }
//		  );
//	  }
////	  if ($("#aWindowInner .mceLayout").length > 0) {
////	    var width = $("#aWindowInner .mceLayout").parent().parent().width();
////	    $("#aWindowInner .mceLayout").width(width - 20);
////	  }  
//	  
  //}
    
  if (inElementIdentifier == "#ajaxID_Notes") {
    ToolTipMagic($("#ajaxID_Notes .jt"));
  }  
  
   if (inElementIdentifier == "#ajaxID_Interests") {
    ToolTipMagic($("#ajaxID_Interests .jt"));
  }    
  
 if (inElementIdentifier == "#ajaxID_ContactHistory") {
    ToolTipMagic($("#ajaxID_ContactHistory .jt"));
  }    
  return false; 
}


function unbindMce(inWrapper) {

   $(inWrapper + " .anMCE").each(
      function(){
        // loop through each mce editor and destroy it.
        tinyMCE.execCommand('mceRemoveControl', true, $(this).attr('id'));
        $(this).remove();
      }
    );
 
}

function unbindWorkAreaTrees(inWrapper) {

   $(inWrapper + " .tree").each(
      function(){
        $(this).hide();
        jQuery.tree.reference($(this).attr('id')).destroy();
      }
    );
 
}

function unBindElements(inElementIdentifier) 
{

  if (inElementIdentifier == "#workAreaUpdate") {
  
    
    if ($(inElementIdentifier + " .tree").length > 0) {
        unbindWorkAreaTrees(inElementIdentifier);
    }
  
    if ($(inElementIdentifier + " .anMCE").length > 0) {
        unbindMce(inElementIdentifier);
    }
  
    if ($("#workAreaUpdate div.codeEditor textarea").length > 0) {
        UnloadCodeEdit($("#workAreaUpdate div.codeEditor textarea"));
    }
    
    
//    if ($("#idFixZIndexoEdit_Center$oEdit").length > 0) {
//      document.getElementById('idFixZIndexoEdit_Center$oEdit').src = "/parts/empty.htm"
//    }
//    
//    if ($("#idFixZIndexoEdit_Center$oEdit1").length > 0) {
//       document.getElementById('idFixZIndexoEdit_Center$oEdit1').src = "/parts/empty.htm"
//    } 
//    
//    if ($("#Center_compare_pinEditor").length > 0) {
//       document.getElementById('Center_compare_pinEditor').src = "/parts/empty.htm"
//    } 
//    
//    if ($("#Center_block_innerBlockRows_compare_pinEditor").length > 0) {
//       document.getElementById('Center_block_innerBlockRows_compare_pinEditor').src = "/parts/empty.htm"
//    }  
//    
//    if ($("#Center_block_innerBlockRows_pinEditor").length > 0) {
//       document.getElementById('Center_block_innerBlockRows_pinEditor').src = "/parts/empty.htm"
//    }       
    
    if ($(".codeEditor").length > 0) {
      $(".codeEditor").remove();
    }
  }
   if (inElementIdentifier == "#aWindowInner") {
      if ($(inElementIdentifier + " .tree").length > 0) {
        unbindWorkAreaTrees(inElementIdentifier);
    }
  }
  return false;
}

function CTabClick(TabPID)
{
CollapseOpen();
Cntrl(TabPID);
}

var passAlertControlStr = "";

function lAlerts(d, passAlertControl)//WORKAREA ALERTS
{
if (IsLoggedOut())
{
$("#ajaxAlertsInline").empty();
return false;
}
 if (d.indexOf("Al",0) > -1) 
 passAlertControlStr = passAlertControl;
 ajaxAlertsInline();
 return false;
}

function ajaxAlertsLoop() {
   if (!IsLoggedOut()) {
    if (!Locked) {
      //ajaxAlerts()
    }
   }
   else {
   // clearTimeout(ajaxAlertLoop);
   }
}

function ajaxAlertsLoopInline() {
   if (!IsLoggedOut()) {
    if (!Locked) {
      ajaxAlertsInline()
    }
   }
   else {
    clearTimeout(ajaxAlertLoopInline);
   }
}

var ajaxAlertLoop;
var ajaxAlertLoopInline;

function ajaxAlerts() {
 
 if (IsLoggedOut()) {
  return false;
 }

    qs = "";
    $("#statusMessages").html("checking for alerts...");
    $.ajax({
     type: "POST",
     url: "/parts/ajaxAlerts.aspx",
     data: qs,
     dataType: "json",
     success: function(d){
      handleJSONalerts(d, 0);
     }
   });
   $("#statusMessages").html("");
  
  if (!ajaxAlertLoop)
  {
    ajaxAlertLoop = setInterval("ajaxAlertsLoop()", 60000);
  }
  return false;
}

function ajaxAlertsInline() {
  AjaxLoad("#ajaxAlertsInline", "/parts/ajaxAlertsInline.aspx?passAlertControl=" + passAlertControlStr,"","loading alerts...","alerts ok",false);
  if (!ajaxAlertLoopInline)
  {
    ajaxAlertLoopInline = setInterval("ajaxAlertsLoopInline()", 60000);
  }
  return false;
}

function lMinf(d)//MODULEINFO
{
if ($("#moduleInfo").length == 0) {
    return false;
}
if (IsLoggedOut())
{
$("#moduleInfo").empty();
return false;
}
 if (d.indexOf("N",0) > -1) 
 AjaxLoad("#moduleInfo", "/parts/moduleinfo.aspx","","loading modules...","module info ok",false);
 return false;
}

function lMo(d)//MODULES
{
    if ($("#moduleGroups").length > 0) {
        if (IsLoggedOut()) 
        {
            $("#moduleGroups").empty();
            return false;
        }
        if (d.indexOf("M",0) > -1) {
            AjaxLoad("#moduleGroups", "/parts/modules.aspx","/js/controls/controls.ModuleDropDown.js","loading modules...","modules ok",false);
        }
        return false; 
    }
    if ($("#objectPanelModules").length > 0) {
        if (IsLoggedOut()) 
        {
            $("#objectPanelModules").empty();
            return false;
        }
        if (d.indexOf("M",0) > -1) {
            AjaxLoad("#objectPanelModules", "/parts/ajaxObjectsPanel.aspx?which=modules","/js/controls/controls.ModuleDropDown.js","loading modules...","modules ok",false);
        }
        return false; 
    }
 
}
  
function lAc(d)//ACTIONS
{
if ($("#actionList").length == 0) {
    return false;
}
if (IsLoggedOut()) 
{
$("#actionList").empty();
return false;
}
 if (d.indexOf("A",0) > -1) 
  AjaxLoad("#actionList", "/parts/actions.aspx","/js/controls/controls.ActionDropDown.js","loading actions...","actions ok",false); 
  
  return false;
}

function lHi(d)//HISTORY
{
if ($("#historyList").length == 0) {
    return false;
}
if (IsLoggedOut())
{ $("#historyList").empty();
return false;
}
 if (d.indexOf("A",0) > -1) 
 AjaxLoad("#historyList", "/parts/history.aspx","/js/controls/controls.HistoryDropDown.js","loading history...","history ok",false); 
 
 return false;
}


function lTaL(d)//TABS LEFT
{
if (IsLoggedOut()) 
{
$("#leftTabs").empty();
return false;
}

 if (d.indexOf("TbL",0) > -1)
  AjaxLoad("#leftTabs", "/parts/tabsLeft.aspx","/js/controls/controls.DropDownTabsLeft.js","loading tabs...","left tabs ok",false);
  
  return false;
}

function lTa(d)//TABS WORKAREA
{
if (IsLoggedOut()) 
{
$("#waTabs").empty();
return false;
}

 if (d.indexOf("TbC",0) > -1)
  AjaxLoad("#waTabs", "/parts/tabs.aspx","/js/controls/controls.DropDownTabs.js","loading tabs...","middle tabs ok",false);
  
  return false;
}

function lTaR(d)//TABS RIGHT
{
if (IsLoggedOut()) 
{
$("#rightTabs").empty();
return false;
}

 if (d.indexOf("TbR",0) > -1)
  AjaxLoad("#rightTabs", "/parts/tabsRight.aspx","/js/controls/controls.DropDownTabsRight.js","loading tabs...","right tabs ok",false);
  
  return false;
}

function lCu(d)//CURRENT USER
{
if (IsLoggedOut()) 
{
$("#currUser").empty();
return false;
}

 if (d.indexOf("C",0) > -1) {
    AjaxLoad("#currUser", "/parts/currentuser.aspx","","loading user details...","user details ok",false);
  }
  return false;
}

function lc(d)//CULTURES LIST
{
if (IsLoggedOut()) 
{
$("#cultureList").empty();
return false;
}

 if (d.indexOf("cul",0) > -1) {
    AjaxLoad("#cultureList", "/parts/cultures.aspx","","loading cultures...","cultures loaded ok",false);
  }
  return false;
}

function lWaL(d)//TREE
{
  if (IsLoggedOut()) 
  {
  $("#workAreaUpdateLeft").empty();
  return false;
  }
   if (d.indexOf("Tascx",0) > -1){
    treeCreate("#workAreaUpdateLeft", "adminTree", "Lid_", "DFC4EDBBDFBA4402923C2A0BCB57FE95", "false", "", "", true, true, true, true, true,'', "ctrl");
    return false;
   }
   if (d.indexOf("Tr",0) > -1){
    AjaxLoad("#workAreaUpdateLeft", "/parts/workarea.aspx?p=0","/js/controls/controls.WorkArea.js","loading work area...","work area ok",false);
    return false;
   }
 return false;
}

function lWa(d) //WORK AREA
{
if (IsLoggedOut()) 
{
$("#workAreaUpdate").empty();
return false;
}

 if (d.indexOf("W",0) > -1)
 { 
   AjaxLoad("#workAreaUpdate", "/parts/workarea.aspx?p=1","/js/controls/controls.WorkArea.js","loading work area...","work area ok",false);
 }
 return false;
}

function lWaR(d) //WORK AREA RIGHT
{
if (IsLoggedOut()) 
{
$("#workAreaUpdateRight").empty();
return false;
}
 if (d.indexOf("V",0) > -1) 
 AjaxLoad("#workAreaUpdateRight", "/parts/workarea.aspx?p=2","","loading right panel...","right panel ok",false);
 AjaxLoad("#ajaxBulkUploadControl", "/parts/ajaxBulkUpload.aspx","","","",false);
  return false;
}

function SetOverallStatus(inStatus)
{

if (IsLoggedOut()) 
{
$("#overallStatus").text("logged out");
return false;
}

switch (inStatus)
 {
 case "Strt":
  //$("#overallStatus").text = '';
  $("#overallStatus").text("requesting...");
  $("#StatusImg").attr("src","/assets/images/common/icons_status/caution_clock_24.png");
  //$("#StatusLoaderImg").attr("src","/assets/images/common/icons_status/ajax-loader.gif");
 break;
 case "Ready":  
  $("#overallStatus").text("ready");
   //$("#StatusLoaderImg").attr("src","/assets/images/common/tiny.gif");
  $("#StatusImg").attr("src","/assets/images/common/icons_status/caution_ok_24.png");
   Locked = false;
   break;
 case "Req":
  $("#overallStatus").text("sending...");
  $("#StatusImg").attr("src","/assets/images/common/icons_status/caution_clock_24.png");
   break;
 case "Resp":
  $("#overallStatus").text("receiving...");
  $("#StatusImg").attr("src","/assets/images/common/icons_status/caution_back_24.png");
   break;
  }
 return false;
}


// stop backspace from hitting the browser unless in an input
// keystroke 8 is the backspace key...

// ie
if (typeof window.event != 'undefined')
document.onkeydown = function()
{

    if(event.keyCode == 8)
    {
        var t = event.srcElement.type;
        
        if(t == 'text' || t == 'textarea' || t == 'password')
        {
            return true;
        }
        return false;
    }
}

// ff etc
else
document.onkeypress = function(e)
{
    if(event.keyCode == 8)
    {
        var t = e.target.type;
        
        if(t == 'text' || t == 'textarea' || t == 'password')
        {
            return true;
        }
        return false;
    }
}

