var MSIE_BROWSER = (navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Win')>=0 && navigator.userAgent.toLowerCase().indexOf('opera')<0)?true:false;
var OPERA_BROWSER = navigator.userAgent.toLowerCase().indexOf('opera')>=0?true:false;

function editEntity(type, id, e) {
  var evtobj = window.event ? event : e;
  /*if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
    alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
  }*/

  // type can be "category" or for items "item/item_type"
  var url = "/iv/cms/edit/"+type+"/"+id;
  url += "?rnd="+new Date().getTime();
  if (evtobj.ctrlKey) {
    temp = siteDomain+type+id;
    var winname = temp.replace(/[^a-zA-Z 0-9]+/g,'');
    window.name = winname;
    window.location.href = url;
  } else {
    launchCMSWindow(url, type, id);
  }
}

function addEntity(type, parentId) {
 // type can be "category" or for items "item/item_type"
  var url = "/iv/cms/add/"+type;
  if (parentId != null) {
    url += "?parent_category_id="+parentId;
  }
  launchCMSWindow(url, type, "add"+parentId);
}

function launchCMSWindow(url, type, id) {
  var w = 1013;
  var h = 770;
  var winl = (screen.width - w) / 2;
  var wint = (screen.height - h) / 2;

  // remove invalid characters
  temp = siteDomain+type+id;
  var winname = temp.replace(/[^a-zA-Z 0-9]+/g,'');
 
  winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',status=0,resizable=1,scrollbars=1';  
  win = window.open(url, winname, winprops);
	win.focus();   
}


function processReqChange() {
}

function CDownloadUrl(method, url, sendContent, func) {
   var httpObj;
   var browser = navigator.appName;
   if(browser.indexOf("Microsoft") > -1)
      httpObj = new ActiveXObject("Microsoft.XMLHTTP");
   else
      httpObj = new XMLHttpRequest();

   // add a rnd param to the url to prevent caching
   if (url.toString().indexOf("?") == -1) {
     url += "?";
   } else {
     url += "&";
   }
   url += "rnd="+new Date().getTime();
   httpObj.open(method, url, true);
   if (sendContent) {
     httpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     httpObj.setRequestHeader("Content-length", sendContent.length);
     httpObj.setRequestHeader("Connection", "close");
   }
   httpObj.onreadystatechange = function() {
      if(httpObj.readyState == 4){        
         if (httpObj.status == 200) {
            var contenttype = httpObj.getResponseHeader('Content-Type');
            if (contenttype.indexOf('xml')>-1) {            
               func(httpObj.responseXML);
            } else {
               func(httpObj.responseText);
            }
         } else {
            func(null);
         }
      }
   };
   httpObj.send(sendContent);
}

function sendXMLHttpRequest(url) {
  req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    try {
       req = new XMLHttpRequest();
    } catch(e) {
      req = false;
    }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
           req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
               req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
               req = false;
            }
        }
    }

    if(req) {
       req.onreadystatechange = processReqChange;
       req.open("GET", url, true);
       req.send("");
    }
}

var URL = {
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string)).replace(/\+/g, " ");
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

      if (c == 32) {
        utftext += "+";
      } else if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}
}

function removeEvent(obj,type,fn){
  if(obj.removeEventListener) obj.removeEventListener(type,fn,false);
  else if(obj.detachEvent){
    obj.detachEvent("on"+type,obj[type+fn]);
    obj[type+fn]=null;
    obj["e"+type+fn]=null;
  }
}

function addEvent(obj,type,fn){
    if(obj.addEventListener) obj.addEventListener(type,fn,false);
    else if(obj.attachEvent){
        obj["e"+type+fn]=fn;
        obj[type+fn]=function(){obj["e"+type+fn](window.event);}
        obj.attachEvent("on"+type,obj[type+fn]);
    }
}

function ding()
{
  document.getElementById("beep").innerHTML = ' <EMBED SRC="/ivcms/audio/ding.wav" WIDTH=1 HEIGHT=1 HIDDEN="true" AUTOSTART="true" LOOP="false" volume="100">';
}


function idleTimeoutAlert() {
    idleTimeoutAlertCountdown = true;
    document.getElementById("timeoutTimerDisplay").innerHTML = " -:--";
    window.focus();
    var idleTimeoutPopUp = document.getElementById("idleTimeoutWindow");    
    ding();
    idleTimeoutPopUp.style.display = "block";
    idleTimeoutPopUp.scrollIntoView(true);
    addEvent(window, 'scroll', function(event) {
      document.getElementById("idleTimeoutWindow").scrollIntoView(true);
    });
    timeoutTimerCountdown = 120000; // 2 minute countdown    
    idleTimeoutTimerIntervalId = setInterval("updateTimeoutTimer()", 1000);
}


var idleTimeoutAlertCountdown = false;
var idleTimeoutTimerIntervalId;
var timeoutTimerCountdown;

function resetIdleTimer() {
    idleTimeoutAlertCountdown = false;
    var idleTimeoutPopUp = document.getElementById("idleTimeoutWindow");
    idleTimeoutPopUp.style.display = "none";
    clearInterval(idleTimeOutId);
    idleTimeOutId = setTimeout("idleTimeoutAlert()",  idleTimoutWarning);
    clearInterval(idleTimeoutTimerIntervalId);
    removeEvent(window, 'scroll', function(event) {
      document.getElementById("idleTimeoutWindow").scrollIntoView(true);
    });  
}

function idleKeepAlive(e) {
  if (!idleTimeoutAlertCountdown) {
    clearInterval(idleTimeOutId);
    idleTimeOutId = setTimeout("idleTimeoutAlert()",  idleTimoutWarning);
  }
}

function updateTimeoutTimer() {
    var timeoutTimerDisplay = document.getElementById("timeoutTimerDisplay");
    var seconds = timeoutTimerCountdown / 1000;
    var minutes = seconds / 60;
    seconds %= 60;
    timeoutTimerDisplay.innerHTML = Math.floor(minutes) + ":" + Math.floor(seconds).numberFormat("00");
    if (timeoutTimerCountdown <= 0) {
      idleTimerExpired();    
    }
    timeoutTimerCountdown = timeoutTimerCountdown - 1000;
    if (timeoutTimerCountdown == 30000) {
        // 30 second warning
        ding();
    }
}

function ivHeartbeat(type) {
 
  var url = "/iv/cms/heartbeat/category?rnd=5";

  if (typeof entityId != "undefined" && typeof entityType != "undefined") {
    // send heartbeat for editing this entity
    url += "&entity_id="+entityId;   
    url += "&entity_type="+entityType;
  }   
  
  CDownloadUrl('get', url, null, function(data) {
    if (data != null && data.getElementsByTagName('heartbeat') != null) {
      var first_element = data.getElementsByTagName('heartbeat').item(0);   // Read the first element
      if (first_element != null) {
         var status = first_element.getAttribute("status");
         //alert(status);
         if (status == "dead") {
           // session has expired
           if (type == "cms") {
             alert("Your ivCMS User Session is no longer active.\n\nClick OK to close this browser window.");
             closeCMSWindow();
           } else {
              alert("You have been logged out of your User Session.");
              window.location.href = "/iv/homepage";
           }
         } else if (status == "lostlock") {
           var lockedBy = first_element.getAttribute("lockedBy");
           alert("WARNING: The Edit LOCK for this Entity has been lost and superseded by "+lockedBy+".\n\nYou will NOT be able to save updates to this Entity if any modifications are made by the superseding User Session.");
         } else if (status == "relocked") {
           // check modify timestamp, if its newer than the beginEditTimestamp in
           // the form, warn user that an update is not possible.
           var staleEntity = true;
           var modifyTimestamp = first_element.getAttribute("modifyTimestamp");
           var editForm = document.getElementById('mainForm');
           if (editForm['beginEditTimestamp'] != undefined) {
             var beginEditTimestamp = editForm['beginEditTimestamp'].value;
             if (beginEditTimestamp > modifyTimestamp) {
               staleEntity = false;
             }
           }
           if (staleEntity) {
             alert("The Edit LOCK for this Entity has been reaquired, however the Entity has been modified since the start of your edit session and is out-of-date.\nYou MUST 'RELOAD' the Entity to obtain the most recent version.");
           } else {
             alert("The Edit LOCK for this Entity has been reaquired.");
           }
         }
      }
    }
    // reset timer
    heartbeatId = setTimeout("ivHeartbeat('"+type+"')", heartbeatTimer);
  });


}

function removeElementFromArray(arrayName,arrayElement)
{
  for(var i=0; i<arrayName.length;i++ )
  {    
    if(arrayName[i]==arrayElement) {   
      arrayName.splice(i,1);
    }
  }
}

function cleanStringParam(dataStr) {
  // cleans string so it is safe for passing as param to javascript function
  // (replaces carrige returns and line breaks with a space and URL encodes)
  return URL.encode(dataStr.replace(/(\r\n|[\r\n])/g, " "));
}

