﻿// JScript File


/// the string.trim function just like in c# 
/// example : StoreNameBox.value.toString().trim()
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };

function handle_system_error(e)
{
    handle_Msg('System Error, please try again.', ''); 
}

function handle_msg(error_msg, displaycontrolid)
{
    alert(error_msg);
    document.getElementById(displaycontrolid).innerHTML = error_msg;
    document.getElementById(displaycontrolid).style.display ="block";
}

function getImgSize_height(imgSrc)
{
    var newImg = new Image();
    newImg.src = imgSrc;
   return newImg.height;
}
function getImgSize_width(imgSrc)
{
    var newImg = new Image();
    newImg.src = imgSrc;
   return newImg.width;
}


function trimXmlTag(res)
{
    var tagHead = '<string xmlns="http://tempuri.org/">';
    var tagTail = '</string>';
    var start = res.search(tagHead) + tagHead.length;
    var end = res.search(tagTail);
    
    return res.substring(res.search(tagHead) + tagHead.length,res.search(tagTail)).unescapeHTML();
}


function CallPrototypeAjax(servicefunctionname, onsuccessfunction, param, errordisplaydiv)
{//debugger;
var ds=theBaseJS_GetURL("/ookkii.asmx/"); 
    new Ajax.Request(ds+servicefunctionname,  
    {    
    method:'post', 
    parameters: param,    
    onSuccess: onsuccessfunction,    
    onFailure: function(){
        try{ 
        if(document.getElementById(errordisplaydiv)!=null)
            document.getElementById(errordisplaydiv).innserHTML=Error_PleaseRefresh;
        else
            alert(Error_PleaseRefresh);
            }
          catch(e)
         {
            
         } 
      }
   }
    );
}

function ExtractCoreJSON(res)
{//alert(res.responseText);

    if(trimXmlTag(res.responseText) != null)//res.responseXML.text.evalJSON().NewDataSet.species
    {
        var dataJson=trimXmlTag(res.responseText).evalJSON();
        if(dataJson.NewDataSet!=null)
            return dataJson.NewDataSet.species;//species == the table name
        else
            return dataJson.DocumentElement;
    }
    else
        return null;
}



function setMenuColor(redId,originId1,originId2,originId3)
{
    if(document.getElementById(redId)!=null)
        document.getElementById(redId).style.color = 'red';
        
    if(document.getElementById(originId1)!=null)
        document.getElementById(originId1).style.color = '#003399';
        
    if(document.getElementById(originId2)!=null)
        document.getElementById(originId2).style.color = '#003399';
    
    if(document.getElementById(originId3)!=null)
        document.getElementById(originId3).style.color = '#003399';
}

//getXY文字Show 和hide//#改ToolTip樣式:至Themes>css>.tooltip修改
//所在網頁需存在<div id="tooltip" class ="tooltip"  style="  position :absolute ;"></div>
function getXY(evt,controlid,placeid) 
{
    evt = evt ? evt : (window.event ? window.event : null);               
    var posX = evt.clientX;
    var posY = evt.clientY;
    
    var tooltip = document.getElementById (controlid);
  
    tooltip.style.position ='absolute';
    tooltip.style.zIndex='1';  
      
    tooltip.style.left = posX+(document.documentElement.scrollLeft || document.body.scrollLeft) -50;// + 'px';//event.clientX;//window.event.clientX+(document.documentElement.scrollLeft || document.body.scrollLeft)+15;//取得mouse位置+scrollbar

    tooltip.style.top = posY+(document.documentElement.scrollTop || document.body.scrollTop);//'100px'//window.event.clientY+(document.documentElement.scrollTop || document.body.scrollTop);
    tooltip.style.display ='block';    
   
}

//----好像沒有用到------------------------------------
function hideXY(controlid)
{
    var tooltip = document.getElementById (controlid);
    tooltip.style.display ='none';
}

function showXY(controlid)
{
    document.getElementById (controlid).style.display = 'block';
}

function showModal(url,hei,wid)
{
    window.showModalDialog(url,document,'dialogHeight:' + hei + 'px;dialogWidth:' + wid + 'px;'+ 'resizable:no');
}
//---------------------------------------------------------

function SetListAction(action,hiddenid)
{
    document.getElementById(hiddenid).value=action;
}


/*scripted by by Peter-Paul Koch & Alex Tingle.*/
  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

function showBlock(controlid, hideControlId, showaftercontrolid)
{
  var anchr = document.getElementById(showaftercontrolid);
  var block = document.getElementById (controlid);  
  
//  block.style .position ='absolute';
//  block.style.left = findPosX(anchr);
//  block.style.top = findPosY(anchr) + anchr.clientHeight;  
//  block.style.zIndex='1';  
//  block.style.display ='block';
    var x=findPosX(anchr);
    var y = findPosY(anchr) + anchr.clientHeight;
  modalPopup_show(controlid+'/'+x+'/'+y+'/anchor')

  var controlNameTemp = ['chooseProductNameBox','addcategoryblock','addaccountblock','selectstoreblock'];  
  for(i=0;i<controlNameTemp.length;i++)
  {
    if(controlNameTemp[i]!=controlid)
        document.getElementById(controlNameTemp[i]).style.display='none';
  }
  
  block = document.getElementById (hideControlId);
  if(block != null){

  }
}

function hideblock(controlid, restroreID)
{
 var block = document.getElementById(controlid);
 block.style.display ='none';

  block = document.getElementById (restroreID);
  if(block != null){
      //block.disabled ="";
      block.style.display='block';
  } 
  
  
  BOX_remove(controlid);
}


var modalPopupWindow = '';


function userselected(hidencontrolid, theselectedvalue)
{
    var somecontrol=  document.getElementById(hidencontrolid);
    somecontrol.value = theselectedvalue; 
}

function cancalEvent(ee)
{
    if(ee.preventDefault) 
    {
        ee.preventDefault();
        ee.stopPropagation();
    }   
   else 
   {
        ee.returnValue=false;
        ee.cancel = true; 
    }
}

function checkNumeric(e)
{
   try
   {
       var showId = checkNumeric_showId;
       var enterId = checkBtnEnter_enterId; 
       if(document.addEventListener)    
       {
           if ( (((e.which<48) || (e.which>57) ))&& (e.which !=  46) && (e.which!=0) && (e.which!=8) ) 
           {
                if(e.which!=13)
                { 
                   if(e.preventDefault) 
                   {              
                        e.preventDefault(); 
                        document.getElementById(showId).style.display='block';
                        document.getElementById(showId).innerHTML = '<font color=red>'+shw_pleaseenternumber+'</font>';                
                        //alert('請輸入數字');
                   }
                } 
                else 
                {             
                    cancalEvent(e);
                    document.getElementById(enterId).click();
                }
           }
           else
           {
                document.getElementById(showId).style.display='none';
                document.getElementById(showId).innerHTML = '';
           }     
       
        }
        else if(window.event)
        {
           if ( ( (event.keyCode<48) || (event.keyCode>57) )&& (event.keyCode !=  46) && (event.keyCode!=8)) 
           {
                if(event.keyCode!=13)
               { 
                    window.event.keyCode= '';
                    document.getElementById(showId).style.display='block';
                    document.getElementById(showId).innerHTML = '<font color=red>'+shw_pleaseenternumber+'</font>';
               }
               else
               {
               
                    cancalEvent(window.event);

                    document.getElementById(enterId).click();
                    return;
                }
                //alert('請輸入數字');
           }    
           else
           {
           document.getElementById(showId).style.display='none';
            document.getElementById(showId).innerHTML = '';
           }         
        }
    }
    catch(e)
    {
    }
}
//checkNumericHandle('bkdisplay_txtProductPrice');
var checkNumeric_showId='';
function checkNumericHandle(controlId,showId,enterId)
{

    checkBtnEnter_enterId=enterId;
    checkNumeric_showId=showId;
    if(document.addEventListener)
    {
        document.getElementById(controlId).addEventListener('keypress',checkNumeric,true);
    }
    else 
    {
        checkNumeric(window.event);
    }
   
}

function checkBtnEnter(e)
{
   try
   {
       var enterId = checkBtnEnter_enterId;
       if(document.addEventListener)    
       {
            if(e.which==13)
            {
                cancalEvent(e);
                if(document.getElementById(enterId)!=null)
                    {
                    document.getElementById(enterId).click;
                  return true; }
                else 
                   return false;
            }                       
        }
        else if(window.event)
        {
            if(event.keyCode==13)
            {
                cancalEvent(e);
                if(document.getElementById(enterId)!=null)
                    document.getElementById(enterId).click();
                else 
                   return false;
            }
        }
    }
    catch(e)
    {
        return false;
    }
}

var checkBtnEnter_enterId='';
function checkBtnEnterHandle(controlId,enterId)
{
    checkBtnEnter_enterId=enterId;
    if(document.addEventListener)
    {
        if(document.getElementById(controlId).addEventListener('keypress',
                function(event) {
                 checkBtnEnter(event); 
                  }
                 ,false))
        return true;
        else return false;
    }
    else 
    {
        checkBtnEnter(window.event);
    }
}



var indexuserselectedtabid;
function index_userchangetab(id, css, selectedCss)
{
    //document.getElementById(id).className = css; 
   var thechild;
   if (Prototype.Browser.IE)
       thechild = document.getElementById(id).children;
     else
       thechild = document.getElementById(id).childNodes;
   for(var i = 0; i <  thechild.length; i++)
   {
        thechild[i].className= css;
   }   
   document.getElementById(indexuserselectedtabid).className = selectedCss;
}

function cleardivinnerhtml(controlid)
{
    document.getElementById(controlid).innerHtml ="";
} 


  
    
    function BOX_layout(e){ 
        var a = document.getElementById(e);
        if (document.getElementById('BOX_overlay')==null){ //判斷是否要新建BOX_overlay
            var overlay = document.createElement("div");
            overlay.setAttribute('id','BOX_overlay');
            overlay.onclick=function(){BOX_remove(e);};
            a.parentNode.appendChild(overlay);
        }
        
        //取得Client左上座標,以及寬和高
        var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        var clientWidth;
        
        
        if (window.innerWidth) {
            clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
        } else {
            clientWidth = document.documentElement.clientWidth;
            
        }
        var clientHeight;
        if (window.innerHeight) {
            clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
        } else {
            clientHeight = document.documentElement.clientHeight;
            
       }
        var bo = document.getElementById('BOX_overlay');
        bo.style.left = scrollLeft+'px';
        bo.style.top = scrollTop+'px';
        bo.style.width = clientWidth+'px';
        bo.style.height = (clientHeight+100)+'px';
        bo.style.display="";
        bo.onclick=function(){BOX_remove(e);}
        //Popup定位
        a.style.position = 'absolute';
        a.style.zIndex=101;
        a.style.display="";
        a.style.left = scrollLeft+((clientWidth-a.offsetWidth)/2)+'px';
        a.style.top = scrollTop+((clientHeight-a.offsetHeight)/2)+'px';
        
    }
    
    
     function HideDiv(hide)
    {
        if(document.getElementById(hide)!=null)
        {
            document.getElementById(hide).style.display='none';        
         }
    }
   
     function ShowDiv(shw)
    {
        if(document.getElementById(shw)!=null)
        {
            document.getElementById(shw).style.display='block';        
         }
    } 
    
    function ShowAndHide(show,hide)
    {
        if(document.getElementById(show)!=null && document.getElementById(hide)!=null)
        {
            document.getElementById(hide).style.display='none';        
            document.getElementById(show).style.display='block';
        }
    }

  function chageTab(idarray,nowid)
  {
    for(i=0;i<idarray.length;i++)
    {
        document.getElementById(idarray[i]).className='productdetailNoSelect';
    }   
    document.getElementById(nowid).className='productdetailSelect';
  }

function chgSelect(nowid)
{
    for(i=0;i<idarray2.length;i++)
    {
        document.getElementById(idarray2[i]).style.backgroundColor='#ffe7c8';
    }   
    document.getElementById(nowid).style.backgroundColor='#FFC632';

}

function chgIframe(iframeid,url)
{
    document.getElementById(iframeid).src=url;
}


var tmpHelp='';
function helpClear(id)
{
if(document.getElementById(id).value!='')
    tmpHelp=document.getElementById(id).value;
document.getElementById(id).value='';
}

function helpSet(id)
{
    if(document.getElementById(id).value=='')
        document.getElementById(id).value=tmpHelp;
}

//dynamically to set the event handle function
function addEvent( obj, type, fn ) { 
  if ( obj.attachEvent ) { 
    obj['e'+type+fn] = fn; 
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );} 
    obj.attachEvent( 'on'+type, obj[type+fn] ); 
  } else 
    obj.addEventListener( type, fn, false ); 
} 


// Removes an event from the object
function removeEvent(obj,event_name,func_name){
	if (obj.detachEvent){
		obj.detachEvent("on"+event_name,func_name);
	}else if(obj.removeEventListener){
		obj.removeEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = null;
	}
}

// Stop an event from bubbling up the event DOM
function stopEvent(evt){
	evt || window.event;
	if (evt.stopPropagation){
		evt.stopPropagation();
		evt.preventDefault();
	}else if(typeof evt.cancelBubble != "undefined"){
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	return false;
}

// Get the obj that starts the event
function getElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.currentTarget;
	}
}
// Get the obj that triggers off the event
function getTargetElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.target;
	}
}
// For IE only, stops the obj from being selected
function stopSelect(obj){
	if (typeof obj.onselectstart != 'undefined'){
		addEvent(obj,"selectstart",function(){ return false;});
	}
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function getCaretEnd(obj){

	if(typeof obj.selectionEnd != "undefined"){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToEnd",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// Get the start position of the caret in the object
function getCaretStart(obj){
	if(typeof obj.selectionStart != "undefined"){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToStart",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// sets the caret position to l in the object
function setCaret(obj,l){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(l,l);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',l);
		m.collapse();
		m.select();
	}
}
// sets the caret selection from s to e in the objectd
function setSelection(obj,s,e){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(s,e);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',s);
		m.moveEnd('character',e);
		m.select();
	}
}

/*    Escape function   */
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
/* --- Escape --- */

/* Offset position from top of the screen */
function curTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/* Object Functions */

function replaceHTML(obj,text){
	while(el = obj.childNodes[0]){
		obj.removeChild(el);
	};
	obj.appendChild(document.createTextNode(text));
}



var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


function display(id)
{
    if(document.getElementById(id).style.display=='none')
        document.getElementById(id).style.display='block';
    else
        document.getElementById(id).style.display='none'; 
}

function setCookie(name,value) {

	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : null;

	document.cookie = escape(name) + "=" + escape(value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString()+240)) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == null) ? "" : ("; secure=" + secure));
}
function eliminateSpace(str) {
        return str.replace(/[\s]+/g, "");
}
function delAllCookie(name) {	
	cookieArray = document.cookie.split(";");
	for (var i=0; i<cookieArray.length; i++) {
		thisCookie = cookieArray[i].split("="); 
		cookieName =eliminateSpace( unescape(thisCookie[0]));
		cookieValue =eliminateSpace( unescape(thisCookie[1]));
		if (cookieName !=name ){ 
		 delCookie(cookieName);
		}
	}
	
}
function getCookie(name,flag) {//falg = true for publicXXXX -- must be return value
	var arg = escape(name) + "=";	
	var nameLen = arg.length;
	var cookieLen = document.cookie.length;	
	var i = 0;   	
	while (i < cookieLen) {
		var j = i + nameLen;
		if (document.cookie.substring(i, j) == arg)	
			    return getCookieValueByIndex(j);			    
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	
	if (flag){//in case their is no cookie do the following	
	    var today = new Date()
	    var cooval="public"+today.valueOf()+Math.random();
	    setCookie(name,cooval);
	    return cooval;
	}
	else return "";
}
function delCookie(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	document.cookie = escape(name) + "=" + cval + "; expires=" + exp.toGMTString();
}

function getCookieValueByIndex(startIndex) {
	var endIndex = document.cookie.indexOf(";", startIndex);
	if (endIndex == -1) 
		endIndex = document.cookie.length;
	return document.cookie.substring(startIndex, endIndex);
} 


// get window address parameter
function getParameter ( queryString, parameterName ) {
var parameterName = parameterName + "=";

    if ( queryString.length > 0 ) {

        begin = queryString.indexOf ( parameterName );

        if ( begin != -1 ) {

            begin += parameterName.length;

            end = queryString.indexOf ( "&" , begin );
            if ( end == -1 ) {
                end = queryString.length
            }

            return unescape ( queryString.substring ( begin, end ) );
        }

        return "";
    }
}

function getURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}
