var isIE = 0;

function popRemoveWall(idwall)
{
  if (confirm("Are you sure you want to remove this wall entry?"))
  {
    window.location = 'cmpPublish2.php?r=del&id=' + idwall;
    
  }
  return false;
}

if (document.all)
{
  isIE = 1;
}

/*

Pop permission dialog if given permission not allowed

Used by: cmpPublish2.php

*/

var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;



/*

  Detect and deal with keystrokes

*/


function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function isset(varname){
  return(typeof(window[varname])!='undefined');
}

function fireOnclick(objID)
{
var target=document.getElementById(objID);
if(document.dispatchEvent) { // W3C
    var oEvent = document.createEvent( "MouseEvents" );
    oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, target);
    target.dispatchEvent( oEvent );
    }
else if(document.fireEvent) { // IE
    target.fireEvent("onclick");
    }   
}


function bubbleSort(arr, key)
{
  var x, y, holder;
  // The Bubble Sort method.
  for(x = 0; x < arr.length; x++) {
    for(y = 0; y < (arr.length-1); y++) {
      if (eval(arr[y][key]) > eval(arr[y+1][key])) {
//      alert('swap: ' + arr[y][key] + ' for ' + arr[y+1][key]);
        holder = arr[y+1];
        arr[y+1] = arr[y];
        arr[y] = holder;
      }
    }
  }

  return arr;
}

function cloneArray(arr)
{
  var a = new Array();
  for (var property in arr)
  {
    a[property] = typeof (arr[property]) == 'object' ? cloneArray(arr[property]) : arr[property];
    return a;
  }
}

function clone(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}


function arrayContains(arryA, val)
{
  for (var i = 0; i < arryA.length; i++)
  {
    if (arryA[i] == val)
    {
      return true;
    }
  }
  return false;
}


function trim(str)
{
  return str.replace(/^\s+|\s+$/g,"");
}

/*

Getter/setters: checkbox

*/

function getRand(max)
{
  return Math.floor(Math.random() * max);
}


function checkBoxToBit(chk)
{
  if (chk.checked) { return 1; }
  return 0;
}

function bitToCheckbox(chk, bit)
{
  if (bit)
  {
    chk.checked = true;
    return;
  }
  chk.checked = false;
}

/*

Getter/setters: select box

*/
  
function getSelectedOption(selectbox)
{
  return selectbox[selectbox.selectedIndex].value;
}
  
function getSelectedText(selectbox)
{
  return selectbox[selectbox.selectedIndex].text;
}

function setSelectedOption(selectbox, num)
{
  selectbox.selectedIndex = num;
}

function addOption(selectbox,text,value )
{
  var optn = document.createElement("OPTION");
  optn.text = text;
  optn.value = value;
  selectbox.options.add(optn);
}

function selOption(in_element, in_value)
{
  var list = document.getElementById(in_element);
  if (list && list.options.length)
  {
    for(var i=0; i<list.options.length; i++)
    {
      if(list.options[i].value == in_value)
      {
        list.selectedIndex = i;
        return;
      }
    }
  }
}

this.Sleep = function ZZzzzZZzzzzzzZZZz(naptime){
  naptime = naptime;
  var sleeping = true;
  var now = new Date();
  var alarm;
  var startingMSeconds = now.getTime();
  while(sleeping){
     alarm = new Date();
     alarmMSeconds = alarm.getTime();
     if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
  }      
}
   
/*

Getter/setters: radio

*/
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

   
   
function isIE()
{
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}
   

var isDebug = 1;

function arrayDump(arr,level)
{
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += arrayDump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
  alert('[[[[[[[[[\n' + dumped_text + '\n]]]]]]]]]');
}

function debugOut(str)
{
  if (isDebug)
  {
    alert('[[[[[[[[[\n' + str + '\n]]]]]]]]]');
  }
}

/*

GreyBox show.  Requires parent document have: gbCloseCancel, gbCloseOK
Don't forget: proxomitron interferes with greybox!

*/

function getBetween(Str, strLeft, strRight)
{
  var strLeftPos = Str.indexOf(strLeft);
  if (strLeftPos == -1) { return ""; }

  var Tmp = Str.substr(strLeftPos + strLeft.length);
  var strRightPos = Tmp.indexOf(strRight);
  if (strRightPos == -1) { return ""; }

  return Tmp.substr(0, strRightPos);
}

function setBetween(str, replace, strLeft, strRight)
{
  var orig = getBetween(str, strLeft, strRight);
  
  var full = strLeft + orig + strRight;
  replace = strLeft + replace + strRight;
  str = str.replace(full, replace);
  return str;
}

function getTimestamp()
{
  var currentTime = new Date();
  return (currentTime.getMonth() + 1) + '/' + currentTime.getDate() + '/' + (currentTime.getYear() + 1900) + " " + currentTime.getHours() + ":" + currentTime.getMinutes();
}

function goURL(url)
{
  window.location = url;
}

function changeClass (elementID, newClass)
{
	var element = document.getElementById(elementID);
	
	element.setAttribute("class", newClass); //For Most Browsers
	element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}

function launchHelpURL(url)
{
  var heiMax = 600;

  var heiMinus = screen.height - 100;
  if (heiMinus < 600) { heiMax = heiMinus; }

  showContainer('/help/help.php?url=' + url, "help", 770, heiMax);
}

function launchHelp(keyword)
{
  var heiMax = 600;

  var heiMinus = screen.height - 100;
  if (heiMinus < 600) { heiMax = heiMinus; }

  showContainer('http://www.teamcomposer.com/help/help.php?title=' + keyword, "help", 770, heiMax);
}

function showContainer(url, nam, wid, hei)
{

  childWindow = open(url, nam, 'scrollbars=yes,resizable=yes,width=' + wid + ",height=" + hei);
//alert(wid + ',' + hei);
  if (childWindow.opener == null)
  {
    childWindow.opener = self;
  }
}

function gbShow(caption, url, height, width)
{
  GB_showCenter(caption, url, height, width);
}

function goHelp(url)
{
  //gbShow('', url, curHeight - 80, curWidth - 128);
  var title = 'Team Composer';

  var rnd = Math.floor(Math.random() * 10000);
  if (url.match(/\?/))
  {
    url += '&';
  }
  else
  {
    url += '?';
  }
  url += "rnd=" + rnd
  
  GB_show(title, url, curHeight - 80, curWidth - 60);
  return false;

}

function goHidden(url)
{
  var rnd = Math.floor(Math.random() * 10000);
  var fd = document.getElementById('iframeHidden');
  fd.src = url + "&rnd=" + rnd;
}

/*

Required by: greybox

*/

var curHeight = -1;
var curWidth = -1;

getSizeBrowser();

function getSizeBrowser()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  curHeight = myHeight;
  curWidth = myWidth;
}

var myHeight = -1;
function resizeBrowser()
{
  getSizeBrowser();
  
  var h = myHeight;
  //if (h != curHeight)
  //{
    //var cc = document.getElementById('ifEditCode');
    //cc.height = h - 52;
  //}
  curHeight = h;



}

function select_all(obj)
{
  var text_val = document.getElementById(obj);
  
  text_val.focus();
  text_val.select();
  
  if (!document.all)
    return; // IE only
  r = text_val.createTextRange();
}

function copy_clipboard(obj)
{
  var text_val = document.getElementById(obj);

  text_val.focus();
  text_val.select();

  text_val = eval(obj);
  arrayDump(text_val);

  Copied = text_val.innerText.createTextRange();
  arrayDump(Copied);
  Copied.execCommand("Copy");
}





function limitChars(textarea, limit, infodiv)
{
  var text = textarea.value; 
  var textlength = text.length;
  var info = document.getElementById(infodiv);

  if(textlength > limit)
  {
    info.innerHTML = 'You cannot write more then '+limit+' characters!';
    textarea.value = text.substr(0, limit);
    return false;
  }
  else
  {
    info.innerHTML = 'You have ' + (limit - textlength) +' characters left.';
    return true;
  }
}




//////////////////////////////////// xml2array() ////////////////////////////////////////
//See http://www.openjs.com/scripts/xml_parser/
var not_whitespace = new RegExp(/[^\s]/);//This can be given inside the funciton - I made it a global variable to make the scipt a little bit faster.
var parent_count;
//Process the xml data
function xml2array(xmlDoc,parent_count) {
	var arr;
	var parent = "";
	parent_count = parent_count || new Object;

	var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
	*	If 1, Value and Attribute will be shown inside the tag - like this...
	*	For the XML string...
	*	<guid isPermaLink="true">http://www.bin-co.com/</guid>
	*	The resulting array will be...
	*	array['guid']['value'] = "http://www.bin-co.com/";
	*	array['guid']['attribute_isPermaLink'] = "true";
	*	
	*	If 0, the value will be inside the tag but the attribute will be outside - like this...	
	*	For the same XML String the resulting array will be...
	*	array['guid'] = "http://www.bin-co.com/";
	*	array['attribute_guid_isPermaLink'] = "true";
	*/

if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
if(xmlDoc.childNodes.length > 1) { //If its a parent
arr = new Object;
parent = xmlDoc.nodeName;

}
else if (xmlDoc.childNodes.length == 1 && xmlDoc.childNodes[0].nodeType != 3){ //TEXT_NODE: 3
arr = new Object;
parent = xmlDoc.nodeName;
}

}
	var value = xmlDoc.nodeValue;
	if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
		if(not_whitespace.test(value)) {//If its a child
			arr = new Object;
			arr[xmlDoc.parentNode.nodeName] = value;
		}
	}

	if(xmlDoc.childNodes.length) {
		if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
			arr = xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
		} else { //If there is more than one childNodes, go thru them one by one and get their results.
			var index = 0;

			for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
				var temp = xml2array(xmlDoc.childNodes[i],parent_count); //:RECURSION:
				if(temp) {
					var assoc = false;
					var arr_count = 0;
					for(key in temp) {
						if(isNaN(key)) assoc = true;
						arr_count++;
						if(arr_count>2) break;//We just need to know wether it is a single value array or not
					}

					if(assoc && arr_count == 1) {
						if(arr[key]) { 	//If another element exists with the same tag name before,
										//		put it in a numeric array.
							//Find out how many time this parent made its appearance
							if(!parent_count || !parent_count[key]) {
								parent_count[key] = 0;

								var temp_arr = arr[key];
								arr[key] = new Object;
								arr[key][0] = temp_arr;
							}
							parent_count[key]++;
							arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
						} else {
							parent_count[key] = 0;
							arr[key] = temp[key];
							if(xmlDoc.childNodes[i].attributes && xmlDoc.childNodes[i].attributes.length) {
								for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
									var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
									if(nname) {
										/* Value and Attribute inside the tag */
										if(attribute_inside) {
											var temp_arr = arr[key];
											arr[key] = new Object;
											arr[key]['value'] = temp_arr;
											arr[key]['attribute_'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										} else {
										/* Value in the tag and Attribute otside the tag(in parent) */
											arr['attribute_' + key + '_' + nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										}
									}
								} //End of 'for(var j=0; j<xmlDoc. ...'
							} //End of 'if(xmlDoc.childNodes[i] ...'
						}
					} else {
						arr[index] = temp;
						index++;
					}
				} //End of 'if(temp) {'
			} //End of 'for(var i=0; i<xmlDoc. ...'
		}
	}

	if(parent && arr) {
		var temp = arr;
		arr = new Object;
		
		arr[parent] = temp;
	}
	return arr;
}


//V3.01.A - http://www.openjs.com/scripts/jx/
jx = {
	//Create a xmlHttpRequest object - this is the constructor. 
	getHTTPObject : function() {
		var http = false;
		//Use IE's ActiveX items to load the file.
		if(typeof ActiveXObject != 'undefined') {
			try {http = new ActiveXObject("Msxml2.XMLHTTP");}
			catch (e) {
				try {http = new ActiveXObject("Microsoft.XMLHTTP");}
				catch (E) {http = false;}
			}
		//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
		} else if (window.XMLHttpRequest) {
			try {http = new XMLHttpRequest();}
			catch (e) {http = false;}
		}
		return http;
	},
	
	// This function is called from the user's script. 
	//Arguments - 
	//	url	- The url of the serverside script that is to be called. Append all the arguments to 
	//			this url - eg. 'get_data.php?id=5&car=benz'
	//	callback - Function that must be called once the data is ready.
	//	format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
	//			the string will be 'eval'ed before returning it. Default:'text'
	//	method - GET or POST. Default 'GET'
	load : function (url,callback,format,method, opt) {
		var http = this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
		if(!http||!url) return;
		//XML Format need this for some Mozilla Browsers
		if (http.overrideMimeType) http.overrideMimeType('text/xml');

		if(!method) method = "GET";//Default method is GET
		if(!format) format = "text";//Default return type is 'text'
		if(!opt) opt = {};
		format = format.toLowerCase();
		method = method.toUpperCase();
		
		//Kill the Cache problem in IE.
		var now = "uid=" + new Date().getTime();
		url += (url.indexOf("?")+1) ? "&" : "?";
		url += now;

		var parameters = null;

		if(method=="POST") {
			var parts = url.split("\?");
			url = parts[0];
			parameters = parts[1];
		}
		http.open(method, url, true);

		if(method=="POST") {
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", parameters.length);
			http.setRequestHeader("Connection", "close");
		}

		var ths = this;// Closure
		if(opt.handler) { //If a custom handler is defined, use it
			http.onreadystatechange = function() { opt.handler(http); };
		} else {
			http.onreadystatechange = function () {//Call a function when the state changes.
				if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
					if(http.status == 200) {
						var result = "";
						if(http.responseText) result = http.responseText;
						//If the return is in JSON format, eval the result before returning it.
						if(format.charAt(0) == "j") {
							//\n's in JSON string, when evaluated will create errors in IE
							result = result.replace(/[\n\r]/g,"");
							result = eval('('+result+')');

						} else if(format.charAt(0) == "x") { //XML Return
							result = http.responseXML;
						}

						//Give the data to the callback function.
						if(callback) callback(result);
					} else {
						if(opt.loadingIndicator) document.getElementsByTagName("body")[0].removeChild(opt.loadingIndicator); //Remove the loading indicator
						if(opt.loading) document.getElementById(opt.loading).style.display="none"; //Hide the given loading indicator.
						
						if(error) error(http.status);
					}
				}
			}
		}
		http.send(parameters);
	},
	bind : function(user_options) {
		var opt = {
			'url':'', 			//URL to be loaded
			'onSuccess':false,	//Function that should be called at success
			'onError':false,	//Function that should be called at error
			'format':"text",	//Return type - could be 'xml','json' or 'text'
			'method':"GET",		//GET or POST
			'update':"",		//The id of the element where the resulting data should be shown. 
			'loading':"",		//The id of the loading indicator. This will be set to display:block when the url is loading and to display:none when the data has finished loading.
			'loadingIndicator':"" //HTML that would be inserted into the document once the url starts loading and removed when the data has finished loading. This will be inserted into a div with class name 'loading-indicator' and will be placed at 'top:0px;left:0px;'
		}
		for(var key in opt) {
			if(user_options[key]) {//If the user given options contain any valid option, ...
				opt[key] = user_options[key];// ..that option will be put in the opt array.
			}
		}
		
		if(!opt.url) return; //Return if a url is not provided

		var div = false;
		if(opt.loadingIndicator) { //Show a loading indicator from the given HTML
			div = document.createElement("div");
			div.setAttribute("style","position:absolute;top:0px;left:0px;");
			div.setAttribute("class","loading-indicator");
			div.innerHTML = opt.loadingIndicator;
			document.getElementsByTagName("body")[0].appendChild(div);
			this.opt.loadingIndicator=div;
		}
		if(opt.loading) document.getElementById(opt.loading).style.display="block"; //Show the given loading indicator.
		
		this.load(opt.url,function(data){
			if(opt.onSuccess) opt.onSuccess(data);
			if(opt.update) document.getElementById(opt.update).innerHTML = data;
			
			if(div) document.getElementsByTagName("body")[0].removeChild(div); //Remove the loading indicator
			if(opt.loading) document.getElementById(opt.loading).style.display="none"; //Hide the given loading indicator.
		},opt.format,opt.method, opt);
	},
	init : function() {return this.getHTTPObject();}
}


// See http://binnyva.blogspot.com/2005/10/dump-function-javascript-equivalent-of.html
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	if (level > 10) return level_padding + "*Maximum Depth Reached*\n"; //Too much recursion preventer

	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}
