
/**
** FILE: functions.js
**
** DESCRIPTION: 
**	Contains general purpose functions used throughout the site
**
*/

function IsIE()
{
	return (navigator.appName == "Microsoft Internet Explorer");
}

function ShowById(id, disp)
{
	if (disp == null) disp = 'block';
	var obj = document.getElementById(id);
	obj.style.display = disp;
}

function CloneObject(what) {
    for (i in what) {
        if (typeof what[i] == 'object') {
            this[i] = new CloneObject(what[i]);
        }
        else
            this[i] = what[i];
    }
}				

function DetectTimeZone()
{
	var tzones = { '-11.5':'NUT', '-11':'SST', '-10':'HST', '-9':'AKST', '-8':'PST', '-7':'MST', '-6':'CST', '-5':'EST', '-4':'AST', '-3.5':'NST', '-3':'ART', '-2':'FNT', '-1':'WET', '0':'GMT', '1':'CET', '2':'IST', '3':'MSK', '4':'IRST', '4.5':'AFT', '5':'PKT', '6':'BDT', '6.5':'MMT', '7':'SGT', '8':'KST', '9':'JST', '10':'ChST', '11':'SBT', '12':'FJT' };
;
	var today = new Date();
	var offset = new Date().getTimezoneOffset() / 60 * -1; 
	return (tzones[offset]);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


function GetBrowserSize() {
  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;
  }
  return [ myWidth, myHeight ];
}

function GetBrowserScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function GetBrowserCenter()
{
	var dim = GetBrowserSize();
	var off = GetBrowserScrollXY();
	var cenX = off[0] + dim[0]/2;
	var cenY = off[1];// + dim[1]/2;
	return [ cenX, cenY ];
}

function var_dump(data,addwhitespace,safety,level) {
   var rtrn = '';
   var dt,it,spaces = '';
   if(!level) {level = 1;}
   for(var i=0; i<level; i++) {
      spaces += '   ';
   }//end for i<level
   if(typeof(data) != 'object') {
      dt = data;
      if(typeof(data) == 'string') {
         if(addwhitespace == 'html') {
            dt = dt.replace(/&/g,'&amp;');
            dt = dt.replace(/>/g,'&gt;');
            dt = dt.replace(/</g,'&lt;');
         }//end if addwhitespace == html
         dt = dt.replace(/\"/g,'\"');
         dt = '"' + dt + '"';
      }//end if typeof == string
      if(typeof(data) == 'function' && addwhitespace) {
         dt = new String(dt).replace(/\n/g,"\n"+spaces);
         if(addwhitespace == 'html') {
            dt = dt.replace(/&/g,'&amp;');
            dt = dt.replace(/>/g,'&gt;');
            dt = dt.replace(/</g,'&lt;');
         }//end if addwhitespace == html
      }//end if typeof == function
      if(typeof(data) == 'undefined') {
         dt = 'undefined';
      }//end if typeof == undefined
      if(addwhitespace == 'html') {
         if(typeof(dt) != 'string') {
            dt = new String(dt);
         }//end typeof != string
         dt = dt.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
      }//end if addwhitespace == html
      return dt;
   }//end if typeof != object && != array
   for (var x in data) {
      if(safety && (level > safety)) {
         dt = '*RECURSION*';
      } else {
         try {
            dt = var_dump(data[x],addwhitespace,safety,level+1);
         } catch (e) {continue;}
      }//end if-else level > safety
      it = var_dump(x,addwhitespace,safety,level+1);
      rtrn += it + ':' + dt + ',';
      if(addwhitespace) {
         rtrn += '\n'+spaces;
      }//end if addwhitespace
   }//end for...in
   if(addwhitespace) {
      rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
   } else {
      rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
   }//end if-else addwhitespace
   if(addwhitespace == 'html') {
      rtrn = rtrn.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
   }//end if addwhitespace == html
   return rtrn;
}//end function var_dump


// Pre-load "working" image
var workingImg = new Image();
workingImg.src = '../img/working.gif';


function CreateWorkingImageDiv(imgWidth, imgHeight, width, height)
{
	if (!imgWidth)  width = 100;
	if (!imgHeight) height = 19;
	if (!width)  width = imgWidth;

	// Create image object
	var imgObj 				= new Image();
	imgObj.src 				= '../img/working.gif';
	imgObj.className		= 'workingimg';
	imgObj.style.width		= imgWidth+'px';
	imgObj.style.height		= imgHeight+'px';
	
	// Create image object container
	var imgDiv 				= document.createElement('div');
	imgDiv.appendChild(imgObj);		// Add image to div container
	imgDiv.className		= 'workingimg';
	imgDiv.style.width		= width+'px';
	if (height) imgDiv.style.height	= height+'px';

	return (imgDiv);
}

/**
  * Replaces an html element with the "working" animated gif
  * Deprecated. Using jquery now instead.
  */
function ReplaceWithWorkingImage(id, width, height)
{
	return;
}

function adjust_textarea_rows(t, extra)
{
	var lines = t.value.split('\n') || [];
	var newRows = lines.length;
	var oldRows = t.rows;
	for (var i = 0; i < lines.length; i++)
	{ 
		var line = lines[i]; 
		if (line.length >= t.cols) 
			newRows += Math.floor(line.length / t.cols);
	}
	if (newRows >= t.rows) t.rows = newRows + extra;
	if (newRows < t.rows) t.rows = Math.max(1, newRows) + extra;
	/* i add extra to above, in case I want a trailing whitespace. */
}

function AutosizeTextAreaJQuery(wrapper, extra) {
	return adjust_textarea_rows(wrapper.get(0), extra);
}

function AutosizeTextAreaPrototype(box) {
	if (box.value == undefined)
		return;
	
	var lines =  box.value.split('\n');
	var rows = 0;
	lines.each(function(line){
		len = line.length;
		rows += 1 + Math.floor(len/box.cols);
	});
	if (rows < 1) rows = 1;
	if (IsIE()) rows++;
	
	box.rows = rows;
}

/* functions for adding and deleting rows for editing classifieds and others */
function AddRow(tableId)
{
	var tableBody = document.getElementById(tableId).tBodies[0];
	numRows = tableBody.rows.length;
	var lastRow = tableBody.rows[numRows-1];
	var newRow = lastRow.cloneNode(true);
	var newRowId = "row_" + numRows;
	newRow.id = newRowId;
	tableBody.appendChild(newRow);
}
function DelRow(tableId, rowObj)
{
	var tableBody = rowObj.parentNode;
	if (tableBody.rows.length > 1) {
		tableBody.deleteRow(rowObj.rowIndex-1);
	}
}

function Add2Rows(tableId)
{
	var tableBody = document.getElementById(tableId).tBodies[0];
	numRows = tableBody.rows.length;
	var secondLastRow = tableBody.rows[numRows-2];
	var newRow = secondLastRow.cloneNode(true);
	var newRowId = "row_" + numRows;
	newRow.id = newRowId;
	var lastRow = tableBody.rows[numRows-1];
	var secondNewRow = lastRow.cloneNode(true);
	numRowsPlus = numRows + 1;
	var secondNewRowId = "row_" + numRowsPlus;
	secondNewRow.id = secondNewRowId;
	tableBody.appendChild(newRow);
	tableBody.appendChild(secondNewRow);
}

function Del2Rows(tableId, rowObj)
{
	var tableBody = rowObj.parentNode;
	if (tableBody.rows.length > 3) {
		tableBody.deleteRow(rowObj.rowIndex);
		tableBody.deleteRow(rowObj.rowIndex-1);
	}
}

/**
 * Function that generically executes a json service
 *
 * PARAMETERS:
 *   svcUrl: the url to the json service, in GET format
 *   responseContainer: the container that the "working" image and result message are created in, typically a "div"
 *   successMsg: (optional) the message to display upon success
 *   failureMsg: (optional) the message to display upon failer
 *
 * Currently only used by functions/search.php/PrintToonResultRows
 */
function ExecService(svcUrl, responseContainer, successMsg, failureMsg)
{
	var container = $(responseContainer);
	if (!successMsg) successMsg = "Update sucessful";
	if (!failureMsg) failureMsg = "Update failed";

	var imgDiv = CreateWorkingImageDiv(200, 15, 230);
	imgDiv.style.position = 'absolute';
	imgDiv.style.display = 'inline';
	imgDiv.style.background = "#FFF";
	imgDiv.style.padding = "10px";
	imgDiv.style.border = "1px solid #234";
	imgDiv.style.textAlign = "center";
	imgDiv.style.fontWeight = "bold";
	imgDiv.style.fontSize = "10px";
	container.appendChild(imgDiv);	// show the image

	// Call json service, will execute ShowUpdateResult callback 
	http('GET', svcUrl, null, 'ShowUpdateResult', 
		 { container: container, imgDiv: imgDiv, successMsg: successMsg, failureMsg: failureMsg } );
}

function ShowUpdateResult(retval, divs)
{
	if (parseInt(retval) == 1) {
		divs.imgDiv.className = "highlightgreen";
		divs.imgDiv.innerHTML = divs.successMsg;
	} else {
		divs.imgDiv.className = "highlightred";
		divs.imgDiv.innerHTML = divs.failureMsg;
	}
	new Effect.Fade(divs.imgDiv, { delay: 2.0 });		// Fade the result msg
	setTimeout (function() { divs.container.removeChild(divs.imgDiv) }, 3000);	// Later remove it
}