// JavaScript Document

/**
 * dictionary that is used by frontend
 */
var dict	= {
	'id'	: {
		'_NV_SEARCH'		: 'Keyword tidak boleh kosong, mohon isi kembali',
		'_TO_LABEL'			: 'Kepada',
		'_FROM_LABEL'		: 'Dari',
		'_INTRO_LABEL'	: 'Pengantar',
		'_FROM_HELP'		: 'Masukan nama anda',
		'_TO_HELP'			: 'Masukan alamat tujuan email, apabila lebih dari satu alamat, mohon pisahkan dengan koma.',
		'_CLOSE'				: 'Tutup',
		'_EMPTY_EMAIL'	: 'Masukan alamat email yang dituju',
		'_NV_EMAIL'			: 'Mohon betulkan alamat email yang dituju'
	},
	'en-us'	: {
		'_NV_SEARCH'		: 'Keyword can not be left blank, Please correct it',
		'_TO_LABEL'			: 'To',
		'_FROM_LABEL'		: 'From',
		'_INTRO_LABEL'	: 'Intro',
		'_FROM_HELP'		: 'Please enter your name',
		'_TO_HELP'			: 'Please provide the recipient address, if more than one please separated with comma.',
		'_CLOSE'				: 'Close',
		'_EMPTY_EMAIL'	: 'Please enter the email address',
		'_NV_EMAIL'			: 'Please re-check your address'
	}
}

/**
 * showProps
 *
 * Shows the properties of an given object
 *
 * object object
 * return array
 *
 * Use print_ob(), alert_ob() or window_ob() to display the result
 */
function getObjectProperties(item)
{
  var retVal = '';
  for (var prop in item)
  {
    if (item[prop].constructor != Function)
    {
      retVal += prop + ' => ' + item[prop] + "\n";
    }
  }
  return retVal;
}

/**
 * showProps
 *
 * Shows the properties of an given object
 *
 * object object
 * return array
 *
 * Use print_ob(), alert_ob() or window_ob() to display the result
 */
function getUserFunctions()
{
  var retVal = '';
  for (var prop in document)
  {
    if (document[prop].constructor == Function)
    {
      retVal += prop + ' => ' + document[prop] + "\n";
    }
  }
  return document;
}



/**
 * print_ob(), alert_ob(), window_ob()
 *
 * These three functions are different ways to display the result of getObjectProperties()
 * print_ob uses document.write and can hence only be called onload
 * alert_ob displays the result in an alert box
 * window_ob opens a popup window and writes the results there
 */
function alert_ob(expr)
{
  alert(getObjectProperties(expr))
}

function window_ob(expr)
{
  win = window.open('', 'format','width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable');
  win.document.open();
  win.document.write('<pre>' + getObjectProperties(expr) + '</pre>');
  win.document.close()
  win.focus();
}

function print_ob(expr)
{
  document.write('<pre>' + getObjectProperties(expr) + '</pre>');
}


/**
 * format_r
 *
 * Returns human-readable information about a variable
 *
 * format_r() returns information about a variable in a way that's readable by humans.
 * If given a string, integer or float, the value itself will be printed.
 * If given an array, values will be presented in a format that shows keys and elements.
 *
 * example:
 *   test = new Array ('foo', 'bar', 'foobar')
 *   format_r(test)
 *   returns: Array
 *            {
 *                 [0] => foo
 *                 [1] => bar
 *                 [3] => foobar
 *            }
 *
 */
function format_r(expr)
{
  var dim    = 0;
  var padVal = '\xA0\xA0\xA0\xA0\xA0';

  switch(typeof expr)
  {
    case 'string':
    case 'number':
      retVal = expr;
      break;
    case 'object':
      retVal = 'Array\n{\n' + outputFormat(expr, dim) + '\n}';
      break;
    default:
      retVal = false;
  }

  function pad(dim)
  {
    padding = '';
    for (i = 0; i < dim; i++)
    {
      padding += padVal;
    }
    return padding;
  }

  function outputFormat(expr, dim)
  {
    var retVal = '';
    for (var key in expr)
    {
        if (typeof expr[key] == 'object' && expr[key].constructor == Array)
        {
          retVal += padVal + pad(dim) + '[' + key + '] => Array\n'
                  + padVal + pad(dim) + '{\n'
                  + outputFormat(expr[key], dim + 1) + padVal + pad(dim) + '}\n';
        }
        else if (expr[key].constructor == Function)
        {
          continue;
        }
        else
        {
          retVal = retVal + padVal + pad(dim) + '[' + key + '] => ' + expr[key] + '\n';
        }
    }
    return retVal;
  }
  return retVal;
}

/**
 * print_r(), alert_r(), window_r()
 *
 * These three functions are just different ways to display the result of format_r()
 * print_r uses document.write and can hence only be called onload
 * alert_r displays the result in an alert box
 * window_r opens a popup window and writes the results there
 */
function alert_r(expr)
{
  alert(format_r(expr))
}

function window_r(expr)
{
  win = window.open('', 'format','width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable');
  win.document.open();
  win.document.write('<pre>' + format_r(expr) + '</pre>');
  win.document.close()
  win.focus();
}

function print_r(expr)
{
  document.write('<pre>' + format_r(expr) + '</pre>');
}

/**
 * _COOKIE is the equivalent to PHP's $_COOKIE
 * An associative array of variables passed to the current script
 * via the HTTP COOKIE method. This function is called onload.
 * This means that as soon as this file is included _COOKIE will be available
 *
 * example:
 *   This function is called onload
 *   If two cookies are set, e.g.
 *   foo=yellow and bar=pink
 *   then _COOKIE['foo'] will contain 'yellow'
 *   and  _COOKIE['bar'] will contain 'pink'
 */
function readCookie()
{
  var _COOKIE = new Array()
  var cookieStr = document.cookie ? document.cookie : '';
  var cookieSplit, cookieKey;
  if(cookieStr)
  {
    cookieStr = cookieStr.replace(/; /, ';')
    var cookieArr = cookieStr.indexOf(';') > -1
                  ? cookieStr.split(';')
                  : new Array(document.cookie);
    for(var i = 0; i < cookieArr.length; i++)
    {
      cookieArr[i].indexOf('=') > -1 ? cookieArr[i] : cookieArr[i] + '=';
      cookieSplit = cookieArr[i].split('=');
      cookieKey = cookieSplit[0].charAt(0) == ' '
                ? cookieSplit[0].substring(1, cookieSplit[0].length)
                : cookieSplit[0];
      _COOKIE[cookieKey] = cookieSplit[1].replace(/\+/g, ' ');
    }
  }
  return _COOKIE
}

var _COOKIE = readCookie();

/**
 * addEvent
 * adds cross-browser event listener to an element
 * @param object domEl
 * @param string evt
 * @param pointer function
 * @param boolean useCapture
 */		
function addEvent(domEl, evt, fn, useCapture){
	if (domEl.addEventListener){
		domEl.addEventListener(evt, fn, useCapture);
		return true;
	}
	else if (domEl.attachEvent){
		var ret	= domEl.attachEvent('on' + evt, fn);
		return ret;
	}
	else{
		domEl['on' + evt] = fn;
	}
}

// Example: obj = findObj("image1");

function findObj(theObj, theDoc)
{
  var p, i, foundObj;

  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++)
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);

  return foundObj;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {
		'posX'	: curleft,
		'posY': curtop
	}
}

/**
 * String.ltrim()
 * removes leading spaces from a string
 */
String.prototype.ltrim	= function(){
	return this.replace(/^\s+/, '');
}

/**
 * String.rtrim()
 * remove trailing spaces from a string
 */
String.prototype.rtrim	= function(){
	return this.replace(/\s+$/, '');
}

/**
 * String.trim()
 * remove leading and trailing from a string
 */
String.prototype.trim	= function(){
	return this.ltrim().rtrim();
}

/**
 * String.replaceArray
 * Replaces regular expressions in array with substitutions
 * @access public
 * @param  Array pairs  Associative array; Regular expressions as key, replacements as value
 * @return String Replaced string
 */
String.prototype.replaceArray = function(pairs)
{
  var s = this;
  for(var re in pairs) s = s.replace(new RegExp(re, "ig"), pairs[re]);
  
  return s;
} 

/**
 * String.htmlDecode
 * Decodes HTML-encoded text
 * @access public
 * @return String  String with HTML special characters decoded
 */
String.prototype.htmlDecode = function()
{
  return this.replaceArray({'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"'});
}

/**
 * setClass
 * set set class to a DOM object
 * @param string id
 * @param string className
 */
function setClass(id, className){
	document.getElementById(id).className	= className;
}

/**
 * cascadedStyle
 * get the specific property value from a DOM object that has been set from CSS
 * @param object el
 * @param string cssProperty
 * @param string csspropertyNS
 */
function cascadedStyle(el, cssproperty, csspropertyNS){
	if (el.currentStyle){ //if IE5+
		return el.currentStyle[cssproperty];
	}
	else if (window.getComputedStyle){ //if NS6+
		var elstyle=window.getComputedStyle(el, "");
		return elstyle.getPropertyValue(csspropertyNS);
	}
}

/**
 * hideShowMe
 * make the DOM object visible / invisible
 * @param string DOMId
 */
function hideShowMe(DOMId){
	var dom	= document.getElementById(DOMId);
			dom.style.display = dom.style.display == 'block' || dom.style.display == '' ? 'none' : 'block';
}

/**
 * removeElement
 *
 * remove certain element from its parent (provided by ID)
 * @param string DOMId
 */ 
function removeElement(DOMId){
	var dom	= document.getElementById(DOMId);
			dom.parentNode.removeChild(dom);
}

/**
 * tabHover
 * set class 'tab-hover' to a DOM object
 * @param object obj
 */
function tabHover(obj){
	if (obj){
		obj.className += ' tab-hover';		
	}
	else return;
}

/**
 * tabNormal
 * remove class 'tab-hover' from a DOM object
 * @param object obj
 */
function tabNormal(obj){
	if (obj)
		obj.className	= obj.className.replace(/tab-hover/i, '');		
	else return;
}

/**
 * activateTab
 * set the tab into active
 * @param object obj
 */
function activateTab(obj){
	var articleTab	= document.getElementById('tab-article');
	
	var tabs	= articleTab.getElementsByTagName('li');
	if (tabs.length > 0){
		for (var i = 0; i < tabs.length; i++){
			if (obj.id == tabs[i].id) window.activeIndex	= i;
			tabs[i].className	= 'inactive';
		}
	}
	
	obj.className	= 'active';
	
	showArticle(contentArticle[activeIndex]);
}

/**
 * showArticle
 * set the content article
 * @param object whichArticle
 */
function showArticle(whichArticle){
	
	/**
	 * actually this can be done through document.createElement() and [object].appendChild(), 
	 * but I don't know why it wont work on motherfuckingIE. So I made an alternation by
	 * setting all the value into string.
	 */
//	var h3	= document.createElement('h3');
//			h3.innerHTML	= whichArticle.title;
//	
//	var p	= document.createElement('p');
//			p.innerHTML	= whichArticle.content.htmlDecode();
	var h3	= '<h3>' + whichArticle.title + '</h3>';
	var p		= '<p>' + whichArticle.content.htmlDecode() + '</p>';
		
	var container	= document.getElementById('article-content');
			container.innerHTML	= h3 + p;
//			container.appendChild(h3);
//			container.appendChild(p);
	adjustContainerHeight();
}

/**
 * showEmailBox
 * construct an email form an display it after user clicks the email icon
 */
/*function showEmailBox(){
	if (document.getElementById('e-mail') && !document.getElementById('email')){
		var emailIcon	= document.getElementById('e-mail');
		var pos	= findPos(emailIcon);
		
		var div	= createEmailForm(pos);
		document.getElementsByTagName('body')[0].appendChild(div);
		
		var form	= div.childNodes[0];
		form.elements[2].focus();
	}
	else{ closeEmailForm(); }
}*/
function showEmailBox(){
	if (document.getElementById('e-mail') && !document.getElementById('email')){
		coverScreen('#000000');
		
		var emailIcon	= document.getElementById('e-mail');
		var pos	= findPos(emailIcon);
		
		var div	= createEmailForm(pos);
		document.getElementsByTagName('body')[0].appendChild(div);
		
		makeCenter(div);
		
		var form	= div.childNodes[0];
		form.elements[2].focus();
	}
	else{ closeEmailForm(); }
}

/**
 * onEnter
 * check enter key has been pressed
 * @param object e
 */
function onEnter(e){
	var key	= e.which ? e.which : e.keyCode;
	
	switch (key){
		case 13:
			validateEmail();
			break;
		default:
			break;
	}
}

/**
 * validAddress
 * validate email address according to RFC882, with one dot accepted between words
 * @param string address
 * @return boolean true (if valid) | false (otherwise)
 */
function validAddress(address){
	return address.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/) ?
		true : false;
}

/**
 * sendEmail
 * sending the email
 * @param object form
 */
function sendEmail(form){
	var rm	= new remote();
	
//	var qs	= rm.createQueryString({
//		'nodeId'	: document.getElementById('nodeId').value,
//		'to'			: document.getElementById('email_to').value,
//		'intro'		: document.getElementById('email_intro').value,
//		'cmd'			: document.getElementById('cmd_email').value
//	});
	
//	alert_r(qs);
//	rm.sendRequest('POST', 'content.php', true, qs, 
//		function (){
//			var xh	= rm.xmlHttp;
//			if (xh.readyState == 4){
//				if (xh.status == 200){
//					window_r(xh.responseText);
//				}
//			}
//		}
//	);
	document.getElementById('cmd_email').name	= 'cmd';
	document.getElementById('cmd_email').id	= 'cmd';
	form.submit();
}

/**
 * validateSearch
 * make sure that keyword is inserted
 * @return boolean false (if text box empty)
 */
function validateSearch(form){
	if (form.keyword.value == ''){
		alert (dict[_COOKIE.fl_locale]._NV_SEARCH);
		form.keyword.focus();
		return false;
	}
}

/**
 * setSearchBox
 * add Event to search text box
 */
function setSearchBox(){
	var keyword	= document.getElementById('keyword');
	
	setKeyword();
	addEvent(keyword, 'blur', setKeyword, false);
	addEvent(keyword, 'focus', clearTextBox, false);
}

/**
 * setKeyword
 * set default value for search keyword
 */
function setKeyword(){
	var keyword	= document.getElementById('keyword');
	var cookie	= readCookie();
	if (keyword.value == '' || keyword.value == cookie['searchKeyword']) 
		keyword.value = cookie['searchKeyword'];
}

/**
 * clearTextBox
 * clear the text box
 */
function clearTextBox(){
	var keyword	= document.getElementById('keyword');
	keyword.value	= '';
}

/**
 * openWindow
 * opens up a new window (pop up)
 * @param string url
 * @param string name
 * @param string attributes
 */
function openWindow(url, name, attributes){
	window.open(url, name, attributes);
}

/**
 * adjustContentWidth
 * adjust the width of the article's content according to the section that the article lies in
 */
function adjustContentWidth(){
	if (_COOKIE.pageCmd){
		if (_COOKIE.pageCmd == 'products' || _COOKIE.pageCmd == 'search'){
			var beta_one	= document.getElementById('beta-one');
			var beta_two	= document.getElementById('beta-two');
			
			var width_one	= cascadedStyle(beta_one, 'width', 'width');
			var width_two	= cascadedStyle(beta_two, 'width', 'width');
			
			beta_two.style.display	= 'none';
			beta_one.style.width		= String(parseInt(width_one) + parseInt(width_two)) + 'px';			
		}
	}	
}

/**
 * fixIE6flicker
 *
 * reduce image flicking in IE6
 * @param boolean fix
 */
function fixIE6flicker(fix) {
	/*Use Object Detection to detect IE6*/
	var  m = document.uniqueID /*IE*/
	&& document.compatMode  /*>=IE6*/
	&& !window.XMLHttpRequest /*<=IE6*/
	&& document.execCommand ;
	
	try{
    if(!!m){
    	m("BackgroundImageCache", false, fix) /* = IE6 only */ 
    }
	}catch(err){};
}
fixIE6flicker(true);

function returnFalse(){
	return false;
}

/**
 * adjustContainerHeight
 * 
 * adjusting container height so bottom shadow can be displayed
 */
function adjustContainerHeight(){
	var oHeight	= document.getElementById('inner-container').offsetHeight;
	var object	= document.getElementById('inner-container1');
	var height	= new Number(oHeight) + 15;
	if (window.ActiveXObject)
		object.style.height	= new String(height) + 'px';
	else
		object.style.minHeight	= new String(height) + 'px';
}

/**
 * xDocSize
 *
 * find the maximum width and height of a page
 * @return object contains width and height
 */
function xDocSize()
{
  var b=document.body, e=document.documentElement;
  var esw=0, eow=0, bsw=0, bow=0, esh=0, eoh=0, bsh=0, boh=0;
  if (e) {
    esw = e.scrollWidth;
    eow = e.offsetWidth;
    esh = e.scrollHeight;
    eoh = e.offsetHeight;
  }
  if (b) {
    bsw = b.scrollWidth;
    bow = b.offsetWidth;
    bsh = b.scrollHeight;
    boh = b.offsetHeight;
  }
//  alert('compatMode: ' + document.compatMode + '\n\ndocumentElement.scrollHeight: ' + esh + '\ndocumentElement.offsetHeight: ' + eoh + '\nbody.scrollHeight: ' + bsh + '\nbody.offsetHeight: ' + boh + '\n\ndocumentElement.scrollWidth: ' + esw + '\ndocumentElement.offsetWidth: ' + eow + '\nbody.scrollWidth: ' + bsw + '\nbody.offsetWidth: ' + bow);
  return {
  	w:Math.max(esw,eow,bsw,bow),
  	h:Math.max(esh,eoh,bsh,boh)
  };
}

/**
 * xScrollTop
 *
 * determine how far window / an element has scrolled vertically 
 */
function xScrollTop(e, bWin)
{
  var offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    var w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;
    else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;
  }
  else {
    e = document.getElementById(e);
    if (e && xNum(e.scrollTop)) offset = e.scrollTop;
  }
  return offset;
}

/**
 * xDef
 *
 * Determine if all arguments are 'defined'.
 */
function xDef()
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}

/**
 * xNum
 *
 * Determine if the arguments are of type Number.
 */
function xNum()
{
  for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}
  return true;
}

/**
 * makeCenter
 *
 * force an element to have center-alignment on the screen
 * @param object elm
 */ 
function makeCenter(elm){
	var cHeight	= Number(window.screen.availHeight) + xScrollTop();
	var cWidth	= Number(window.screen.availWidth);
	var eHeight	= Number(elm.offsetHeight);
	var eWidth	= Number(elm.offsetWidth);
	
	elm.style.top		= String(((cHeight / 2) - (eHeight / 2))) + 'px';
	elm.style.left	= String((cWidth / 2)- (eWidth / 2)) + 'px';
}
