//==============================================================================
// Some common util functions 
//==============================================================================

// set a value to cookie
function setCookieAttribute(cookieName,cookieValue){
  try{           
   document.cookie = cookieName+'=' + escape(cookieValue)+';' + "path=/;";
  }catch(ex){
  }
}

// get a value to cookie
function getCookieAttribute(cookieName){
  try{
    var cookieString = document.cookie;
    var start = cookieString.indexOf(cookieName + '=');
    if (start <0 ){
        return null;
    }
    start += cookieName.length + 1;
    var end = cookieString.indexOf(';', start);
    var cookieValue = end < 0 ? unescape(cookieString.substring(start)) : unescape(cookieString.substring(start, end));
    return cookieValue;
  }catch(ex){
    return null;
  }
}

/* 2010-07-07 Adam Wong BEGIN */
// delete a cookie
function deleteCookie(cookieName, path, domain) {
	if (getCookieAttribute(cookieName)) {
		document.cookie = cookieName + "=" +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}
/* 2010-07-07 Adam Wong END */

// auto close the current window
function autoCloseWindow(){
	try{
		var closedTime = parseInt(getCookieAttribute('close_window_time'));
		if(openedTime<closedTime){
			window.close();
		}				
	}catch(ex){
		//alert(ex.message);
	}
}

// get value of url's parameter with name 'name'
function gup( url,name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

// add or replace parameter in url
function addOrReplaceParam(url, name, value) {
	try {
		var oldValue = gup(url, name);
		if (oldValue == "") {
			if (url.indexOf('?') != -1) {
				url = url +	'&'	
			} else {
				url = url + '?';
			}
			url = url + name + '=' + value;
		} else {
			url = url.replace ( new RegExp(name+ '=' + oldValue,'gm'),name+'=' +value);		
		}
	} catch (e) {
		return url;
	}
	return url;
	
}
// reload main portal page with target siteLang
function reloadPortalPage(obj,lang, isRemoveQueryString) {
	var url = '';
	var isForwardLoginPageUrl = false;
	try {
		if (typeof window.opener != 'undefined' && window.opener) {
			//window.opener.top.location.reload();
			url = window.opener.top.location.href;
		} else {
			//window.top.location.reload();
			url = window.top.location.href;
			if (url.indexOf("download.portlet") != -1) {
				isForwardLoginPageUrl = true;
			}
		}
		// remove '#[...]" at url
		var anchor_index =  url.indexOf('#');
		if (anchor_index != -1) {
			url = url.substring (0, anchor_index);
			
		}
		
		// if required to remove query string
		try {
			if (typeof isRemoveQueryString != 'undefined' && isRemoveQueryString != null && isRemoveQueryString == true) {
				url =  url.substr(0, url.lastIndexOf(window.top.location.search))
			}
		}
		catch (e) {
		}
		
		// add default site lang
		url = addOrReplaceParam (url, 'siteLang', lang);
	
	
		if (isForwardLoginPageUrl) {
			// forward itself to loginPageUrl 
			window.top.location.href = loginPageUrl;		
		} else {
			if (typeof window.opener != 'undefined' && window.opener != null) {
				window.opener.top.location.href =  url;
			} else {
				window.top.location.href = url;
			}	
		}		 
	} catch (e) {
		//alert (e);
	} 
}

/**
 * Checks a given class attribute for the presence of a given class
 *
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     The name of the CSS class to check for
 */
checkForClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (element.className == '') {
        return false;
    } else {
        return new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }
}


/**
 * Adds a class to an element's class attribute
 *
 * @param   element         DOM Element object (or element ID) to add the class to
 * @param   nameOfClass     Class name to add
 * @see     checkForClass
 */
addClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (!checkForClass(element, nameOfClass)) {
        element.className += (element.className ? ' ' : '') + nameOfClass;
        return true;
    } else {
        return false;
    }
}


/**
 * Removes a class from an element's class attribute
 *
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     Class name to remove
 * @see     checkForClass
 */
removeClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (checkForClass(element, nameOfClass)) {
        element.className = element.className.replace(
            (element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),
            '');
        return true;
    } else {
        return false;
    }
}


/**
 * Replaces a class with another if the class is present
 *
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   class1          Class name to replace
 * @param   class2          Class name to replace it with
 * @see     checkForClass
 * @see     addClass
 * @see     removeClass
 */
replaceClass = function(element, class1, class2) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (checkForClass(element, class1)) {
        removeClass(element, class1);
        addClass(element, class2);
        return true;
    } else {
        return false;
    }
}


/**
 * Toggles the specified class on and off
 *
 * @param   element         DOM Element object (or element ID) to toggle the class of
 * @param   nameOfClass     Class name to toggle
 * @see     checkForclass
 * @see     addClass
 * @see     removeClass
 */
toggleClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (checkForClass(element, nameOfClass)) {
        removeClass(element, nameOfClass);
    } else {
        addClass(element, nameOfClass);
    }

    return true;
}

imgout=new Image(9,9);
imgin=new Image(9,9);

/////////////////BEGIN USER EDITABLE///////////////////////////////
	imgout.src="/shkco-web/framework/customs/images/icon_off.jpg";
	imgin.src="/shkco-web/framework/customs/images/icon_on.jpg";
	previousId="";
///////////////END USER EDITABLE///////////////////////////////////

//this switches expand collapse icons
function filter(imagename,objectsrc){
	if (document.images){
		document.images[imagename].src=eval(objectsrc+".src");
	}
}

//show OR hide funtion depends on if element is shown or hidden
function shoh(id) {       
    
  dashId = id + '-1';
  linkId = 'link' + id;
  element = document.getElementById(linkId);
    
  if (document.getElementById) { // DOM3 = IE5, NS6
    if (document.getElementById(id).style.display == "none"){
      if (((navigator.userAgent.indexOf('Firefox')>0)) || ((navigator.userAgent.indexOf('Chrome')>0))) {
        document.getElementById(id).style.display = 'table-row';        
        document.getElementById(dashId).style.display = 'table-row';
      }
      else {
      document.getElementById(id).style.display = 'block';
      document.getElementById(dashId).style.display = 'block';
      }
      filter(("img"+id),'imgin');  
      element.className = "shk-portal-link-ipoFAQ-on";
    } else {
      filter(("img"+id),'imgout');
      document.getElementById(id).style.display = 'none';      
      document.getElementById(dashId).style.display = 'none';
      element.className = 'shk-portal-link-ipoFAQ-off';
    }      
  } else { 
    if (document.layers) {  
      if (document.id.display == "none"){
        if (((navigator.userAgent.indexOf('Firefox')>0)) || ((navigator.userAgent.indexOf('Chrome')>0))) {
        document.id.display = 'table-row';
        document.dashId.display = 'table-row';
        }
        else {
          document.id.display = 'block';
          document.dashId.display = 'block';
        }          
        filter(("img"+id),'imgin');
        element.className='shk-portal-link-ipoFAQ-on';
      } else {
        filter(("img"+id),'imgout');  
        document.id.display = 'none';
        document.dashId.display = 'none';
        element.className='shk-portal-link-ipoFAQ-off';
      }
    } else {
      if (document.all.id.style.visibility == "none"){
        if (((navigator.userAgent.indexOf('Firefox')>0)) || ((navigator.userAgent.indexOf('Chrome')>0))) {
        document.all.id.style.display = 'table-row';
        document.all.dashId.style.display = 'table-row';
        }
        else {
          document.all.id.style.display = 'block';
          document.all.dashId.style.display = 'block';
        }
        document.all.id.style.color='#E10915';
        element.className='shk-portal-link-ipoFAQ-on'
      } else {
        filter(("img"+id),'imgout');
        document.all.id.style.display = 'none';
        document.all.dashId.style.display = 'none';
        element.className = 'shk-portal-link-ipoFAQ-off';
      }
    }    
  }
  
  if (previousId) {
    if (previousId != id) {
      resetShoh(previousId);
    }    
  }
  
  previousId = id;
}

function resetShoh(id) {

  dashId = id + '-1';
  linkId = 'link' + id;
  element = document.getElementById(linkId);
  
  if (document.getElementById) { // DOM3 = IE5, NS6    
      filter(("img"+id),'imgout');
      document.getElementById(id).style.display = 'none';      
      document.getElementById(dashId).style.display = 'none';
      element.className = 'shk-portal-link-ipoFAQ-off';
  } 
  else { 
    if (document.layers) {        
        filter(("img"+id),'imgout');  
        document.id.display = 'none';
        document.dashId.display = 'none';
        element.className='shk-portal-link-ipoFAQ-off';
    } 
    else {      
        filter(("img"+id),'imgout');
        document.all.id.style.display = 'none';
        document.all.dashId.style.display = 'none';
        element.className = 'shk-portal-link-ipoFAQ-off';
    }    
  }  
}

//***********************************************************************************

//	checks whether the strin g is numeric or not ..i.e contains decimal

//***********************************************************************************
function chkStockCode(userValue) {
  return ((!isNaN(parseFloat(userValue))) && (isFinite(userValue)));
}

function chkNumeric(userValue) {
  var frontNum = getFrontNum(userValue);

  return ((!isNaN(parseFloat(userValue))) && (isFinite(userValue)) && (((parseInt(frontNum, 10) + "") == (frontNum + ""))));
}

function getDecPlace(num) {
  var numStr = num + "";
  var decPlace = numStr.split(".")[1];
  if (decPlace == null) {
    decPlace = "";
  }
  return decPlace;
}

function getFrontNum(num) {
  var numStr = num + "";
  var frontNum = numStr.split(".")[0];
  if (frontNum == null) {
    frontNum = 0;
  }
  return frontNum;
}

function formatNumber(num, minDecPlace) {
  num += "";
  if (eval(minDecPlace) > 0) {
    if ((num != "") && (chkNumeric(num))) {
      var decPlace = getDecPlace(num);
      if (decPlace.length <= minDecPlace) {
        if (decPlace.length == 0) {
          num += ".";
        }
        for (var i = decPlace.length; i < minDecPlace; i++) {
          num += "0";
        }
      }
      else {
        var isLoop = true;
        do {
          decPlace = getDecPlace(num);
	
          var curNum = decPlace.substr(decPlace.length - 1, 1);
          if (curNum == "0") {
            num = num.substr(0, num.length - 1);
          }
          else {
            isLoop = false;
          }
				
          decPlace = getDecPlace(num);
        }
        while ((decPlace.length > minDecPlace) && (isLoop));
      }
    }
  }
  else if (eval(minDecPlace) == 0) {
	var dotPos = num.indexOf('.');
	if (dotPos > 0) {
	  num = num.substring(0, dotPos);
	}
  }
	
  return num;
}

function formatStockCode(stockCode) {
  var isNumeric = chkNumeric(stockCode);

  if (isNumeric) {
    stockCode += "";
    var varlen = stockCode.length;
    if ((varlen < 5) && (varlen > 0)) { 
      for (i = 0; i < (5 - varlen); i++) {
        stockCode = "0" + stockCode;
      }
    }
  }
  return stockCode;
}

function showdiv(id) {
  if (document.getElementById) { // DOM3 = IE5, NS6
    if (((navigator.userAgent.indexOf('Firefox')>0)) || ((navigator.userAgent.indexOf('Chrome')>0))) {
      document.getElementById(id).style.display = 'table-row';        
    }
    else {
      document.getElementById(id).style.display = 'block';
    }
  }
} 

function hidediv(id) {
  if (document.getElementById) { // DOM3 = IE5, NS6
    if (((navigator.userAgent.indexOf('Firefox')>0)) || ((navigator.userAgent.indexOf('Chrome')>0))) {
      document.getElementById(id).style.display = 'none';        
    }
    else {
      document.getElementById(id).style.display = 'none';
    }
  }
} 

function makeRequest(container, url) {
    var http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    }
    if (!http_request) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    // ????????? alterContents()
    http_request.onreadystatechange = function() { 
              displayContents(document.getElementById(container),http_request); 
    }
    http_request.open('GET', url, true);
    http_request.send(null);
}

function displayContents(container, http_request) {
    if (http_request.readyState == 4) {
      container.innerHTML = http_request.responseText
    }
}

function formatStockCode(src, target){
    var formattedStockCode = src;
    while (formattedStockCode.length < target) {
        formattedStockCode = "0" + formattedStockCode;
    }
    return formattedStockCode;
}




