// some variables
var divno = 0;
var twitter_reply_div = '';
var prefix = parent.location.protocol;
var host = prefix+"//"+window.location.hostname;
var list_slug_selectbox;

var timeout_count = 0;
function doSearchHelpTimeout(helpsearch) {
  timeout_count = timeout_count + 1;
  setTimeout("doSearchHelpGo(" + timeout_count + ", '" + helpsearch + "')", 500);
}
function doSearchHelpGo(currCount, helpsearch) {
  if(currCount == timeout_count) {
    timeout_count = 0;
    ShowDivInline('help_search_loading');
    new Ajax.Request('ajax_help_articles.php?search=' + helpsearch, {
		  method: 'get',
    	onSuccess: function(transport) {
        HideDiv('help_search_loading');
//        alert('&quot;' + transport.responseText + '&quot;');
        if (transport.responseText!='') {
          EditDiv('help_articles', transport.responseText);
    		}
    	} ,
    	onFailure: function(transport) {
        HideDiv('help_search_loading');
//        alert('Error while searching thru help articles.');
    	}
    });
  }
}

var tweetnow_box_status = 0;
function ShowHideTweetNowBox(tweetnow_button) {
  if (tweetnow_box_status==0) {
    ShowDiv_Effect('tweetnow_div');
    tweetnow_box_status = 1;
    tweetnow_button.innerHTML = 'Hide tweeting box...';
  } else {
    HideDiv_Effect('tweetnow_div');
    tweetnow_box_status = 0;
    tweetnow_button.innerHTML = '<img src="images/thread.png" align="absmiddle" /> Tweet now or Schedule...';
  }
}
function OpenTweetNowBox() {
  ShowDiv('tweetnow_div');
  tweetnow_box_status = 1;
  document.getElementById('tweetnow_button').innerHTML = 'Hide tweeting box...';
  document.getElementById('status').focus();
}

var activesession_pu;
var topusername_pu;
var ratelimitstatus_pu;
var getreplies_pu;
var getdirectmessages_pu;
var dosearch_sidebar_pu;
var getsearchtrends_pu;
var showonlineusers_pics_pu;
var friendstimeline_pe;
function stopAutorefresh() {
	try {
	topusername_pu.stop();
	ratelimitstatus_pu.stop();
	getreplies_pu.stop();
	getdirectmessages_pu.stop();
	dosearch_sidebar_pu.stop();
	getsearchtrends_pu.stop();
	showonlineusers_pics_pu.stop();
	friendstimeline_pe.stop();
	activesession_pu.stop();
	} catch(err) {}
}
function startAutorefresh() {
	try {
	topusername_pu.start();
	ratelimitstatus_pu.start();
	getreplies_pu.start();
	getdirectmessages_pu.start();
	dosearch_sidebar_pu.start();
	getsearchtrends_pu.start();
	showonlineusers_pics_pu.start();
	friendstimeline_pe.start();
	activesession_pu.start();
  new Ajax.Request('trigger_set_activesession.php', {
	  method: 'get'
    });
	} catch(err) {}
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// redirect
function javascript_replaceurl(url) {
  var version = parseInt(navigator.appVersion)
  if (version>=4 && window.location.replace)
    window.location.replace(url);
  else
    window.location.href = url;
}

// addslashes - similar to PHP addslashes function
function addslashes( str ) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +   improved by: marrtins
  // +   improved by: Nate
  // +   improved by: Onno Marsman
  // *     example 1: addslashes("kevin's birthday");
  // *     returns 1: 'kevin\'s birthday'
  return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

// twitter function, to prepare topic string for href link
function twitter_preparetopicforlink(topic) {
  var topic = addslashes(topic);
  topic = topic.replace(' ', '+');
  topic = topic.replace('&amp;', '%26');
  topic = topic.replace('&amp;', '%26');
  return topic;
}

// select/deselect all checkboxes
function SelectAll(formId, CheckBoxControl, groupName) {
  var formObj = document.getElementById(formId);
  if (CheckBoxControl.checked == true)
  {
    var i;
    for (i=0; i < formObj.elements.length; i++) {
      if ((formObj.elements[i].type == 'checkbox') && (formObj.elements[i].name.indexOf(groupName) > -1)) {
        formObj.elements[i].checked = true;
      }
    }
  } else {
    var i;
    for (i=0; i < formObj.elements.length; i++) {
      if ((formObj.elements[i].type == 'checkbox') && (formObj.elements[i].name.indexOf(groupName) > -1)) {
        formObj.elements[i].checked = false;
      }
    }
  }
}

// insert iframe into main body
function InsertFrameContent(divname) {
var _y = document.getElementById(divname);
var _x = window.frames[0].document.body.innerHTML;
_y.innerHTML = _x;
alert(_x);
}

// collapse all DIVs
function CollapseAllDivs(dividpartial){
 var divs = document.getElementsByTagName('div');
 for(i=0;i<divs.length;i++) { 
  if(divs[i].id.indexOf(dividpartial)==0) { 
   HideDiv(divs[i].id);
  }
 }
}

// expand all DIVs
function ExpandAllDivs(dividpartial){
 var divs = document.getElementsByTagName('div');
 for(i=0;i<divs.length;i++) { 
  if(divs[i].id.indexOf(dividpartial)==0) { 
   ShowDiv(divs[i].id);
  }
 }
}

// swap display for specified DIV
function SwapDivDisplay_Effect(divid){
 var o = document.getElementById(divid);
 if(o.style.display == 'none')
  Effect.SlideDown(divid);
 else
  Effect.SlideUp(divid);
}

// show DIV effect
function ShowDiv_Effect(divid){
 var o = document.getElementById(divid);
 Effect.SlideDown(divid);
}

// hide DIV effect
function HideDiv_Effect(divid){
 var o = document.getElementById(divid);
 Effect.SlideUp(divid);
}

// show a DIV
function ShowDiv(divid){
 var o = document.getElementById(divid);
 o.style.display = '';
}

// hide a DIV
function HideDiv(divid){
 var o = document.getElementById(divid);
 o.style.display = 'none';
}

// show a DIV - Inline
function ShowDivInline(divid){
 var o = document.getElementById(divid);
 o.style.display = 'inline';
}

// hide a DIV
function HideDivFade(divname){
 new Effect.Fade(divname,{startcolor:'#cc0000',duration:8.0});
}

// hide a DIV quickly
function HideDivFadeQuick(divname){
 new Effect.Fade(divname,{startcolor:'#cc0000',duration:2.0});
}

// swap display for specified DIV
function SwapDivDisplay(divid){
 var o = document.getElementById(divid);
 if(o.style.display == 'none')
  o.style.display = '';
 else
  o.style.display = 'none';
}

// replace one div content with another div
function SwitchDiv(source, target) {
  var sourceObj = document.getElementById(source);
  var targetObj = document.getElementById(target);
  targetObj.innerHTML = sourceObj.innerHTML;
}

// set other HTML for one DIV
function EditDiv(target, newHTML) {
  var targetObj = document.getElementById(target);
  targetObj.innerHTML = newHTML;
}

// edittravelservices, deselect all destinations in DIV
function counter_deselectall(fieldname) {
  var totElements=fieldname.length;
  for (var i=0; i<totElements; i++){
    thisElement = fieldname[i];
    thisElement.selected = false;
  }
}

// edittravelservices, update destinations DIV
function counter_multiselectfield(fieldname, divname) {
  var totElements=fieldname.length;
  var j=0;
  for (var i=0; i<totElements; i++){
    thisElement = fieldname[i];
    if (thisElement.selected == true) j++;
  }
  var divitem=document.getElementById(divname);
  divitem.innerHTML=j;
}

// execute a script with ajax updater
function execute_script( divname, scriptname, params ) {
  new Ajax.Updater( divname, host+'/'+scriptname+'.php?'+params );
}

/*==================================================
  Cookie functions
  ==================================================*/
function setCookie(name, value, nDays, path, domain, secure) {
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie= name + "=" + escape(value) +
        ((nDays) ? "; expires=" + expire.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// Email Validation Javascript
// copyright 23rd March 2003, by Stephen Chapman, Felgall Pty Ltd
// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.
function validateEmail(addr,man,db) {
if (addr == '' && man) {
   if (db) alert('email address is mandatory');
   return false;
}
if (addr == '') return true;
var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
for (i=0; i<invalidChars.length; i++) {
   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
      if (db) alert('email address contains invalid characters');
      return false;
   }
}
for (i=0; i<addr.length; i++) {
   if (addr.charCodeAt(i)>127) {
      if (db) alert("email address contains non ascii characters.");
      return false;
   }
}
var atPos = addr.indexOf('@',0);
if (atPos == -1) {
   if (db) alert('email address must contain an @');
   return false;
}
if (atPos == 0) {
   if (db) alert('email address must not start with @');
   return false;
}
if (addr.indexOf('@', atPos + 1) > - 1) {
   if (db) alert('email address must contain only one @');
   return false;
}
if (addr.indexOf('.', atPos) == -1) {
   if (db) alert('email address must contain a period in the domain name');
   return false;
}
if (addr.indexOf('@.',0) != -1) {
   if (db) alert('period must not immediately follow @ in email address');
   return false;
}
if (addr.indexOf('.@',0) != -1){
   if (db) alert('period must not immediately precede @ in email address');
   return false;
}
if (addr.indexOf('..',0) != -1) {
   if (db) alert('two periods must not be adjacent in email address');
   return false;
}
var suffix = addr.substring(addr.lastIndexOf('.')+1);
if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
   if (db) alert('invalid primary domain in email address');
   return false;
}
return true;
}

var MAX_DUMP_DEPTH = 10;
function dumpObj(obj, name, indent, depth) {
	  if (depth > MAX_DUMP_DEPTH) {
			 return indent + name + ": <Maximum Depth Reached>\n";
	  }
	  if (typeof obj == "object") {
			 var child = null;
			 var output = indent + name + "\n";
			 indent += "\t";
			 for (var item in obj)
			 {
				   try {
						  child = obj[item];
				   } catch (e) {
						  child = "<Unable to Evaluate>";
				   }
				   if (typeof child == "object") {
						  output += dumpObj(child, item, indent, depth + 1);
				   } else {
						  output += indent + item + ": " + child + "\n";
				   }
			 }
			 return output;
	  } else {
			 return obj;
	  }
}

function object2String(obj) {
    var val, output = "";
    if (obj) {    
        output += "{";
        for (var i in obj) {
            val = obj[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += i + ":" + array2String(val) + ",";
                    } else {
                        output += i + ":" + object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += i + ":'" + escape(val) + "',";
                    break;
                default:
                    output += i + ":" + val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "}";
    }
    return output;
}

function array2String(array) {
    var output = "";
    if (array) {
        output += "[";
        for (var i in array) {
            val = array[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += array2String(val) + ",";
                    } else {
                        output += object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += "'" + escape(val) + "',";
                    break;
                default:
                    output += val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "]";
    }
    return output;
}


function string2Object(string) {
    eval("var result = " + string);
    return result;
}

function string2Array(string) {
    eval("var result = " + string);
    return result;
}

// This function recursively inspects passed objects
// and stores property information in a string. This string is 
// returned after there are no more object properties to examine
function parseObj(obj) {
  objCount = 0;
  var objStr = '';
    for (prop in obj) {
      objStr += '<TR><TD>Property: </TD><TD><B>' + prop + '</B></TD><TD>Type: </TD><TD><B>' + typeof(obj[prop]) + 
        '</B></TD><TD>Value: </TD><TD><B>'  + obj[prop] + '</B></TD></TR>';
      if (typeof(obj[prop]) == "object") {
        objStr += parseObj(obj[prop]);
        }
      }
  return objStr;
  }

// This function displays object properties accumulated from parseObj() 
function objProfile() {
  var objTable = '<TABLE BORDER=2 CELLSPACING=0><TR><TD><H1>Object Profile</H1></TD></TR>';
  for (var i = 0; i < arguments.length; i++) { 
    objTable += '<TR><TD><BR><BR><H2><TT>' + (i + 1) + ') ' + arguments[i] +  '</H2></TD></TR>';
    objTable += '<TR><TD><TT><TABLE CELLPADDING=5>' + parseObj(eval(arguments[i])) + '</TABLE></TD></TR>';
    }
  objTable += '</TABLE><BR><BR><BR>';
  return objTable;
  }
