function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function MM_popupMsg(msg) { //v1.0
    alert(msg);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features).focus();
}

function SYNX_showModalDialog(theURL,args,features) { // added by Clark Lu, 05/15/2003, for modal window
  if(ie) {
    return window.showModalDialog(theURL,args,features);
  }
  else {
    return MM_openBrWindow(theURL,'modal dialog',features);
  }
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function tmd_findObj(n) {
    var x,t; if((n.indexOf("?"))>0&&parent.frames.length){t=n.split("?");
    x=eval("parent.frames['"+t[1]+"'].document.getElementById('"+t[0]+"')");
    }else{x=document.getElementById(n)}return x;
}

function tmd_DivMove(theDiv, l, t) {
    var x = (document.layers) ? ".left" : ".style.left";
    var y = (document.layers) ? ".top" : ".style.top";
    var fun = (document.getElementById) ? "tmd_findObj" : "MM_findObj";
    var obj = eval(fun+"(theDiv)");
    if(obj) {
      if(l) eval(fun+"('"+theDiv+"')"+x+"="+l);
      if(t) eval(fun+"('"+theDiv+"')"+y+"="+t);
    }
}

function tmd_SwitchDiv(theDiv, l1, l2, t1, t2) { // written by Clark Lu, switch div between two positions
    var x = ".style.left";
    var y = ".style.top";
    
    var fun = (document.getElementById) ? "tmd_findObj" : "MM_findObj";
    var obj = eval(fun+"(theDiv)");
    if(obj){
    	
      if(l1) {
        var oldL = eval(fun+"('"+theDiv+"')"+x);
        //oldL = (oldL.substring(0, oldL.indexOf('px'))==(""+l1)) ? l2 : l1;
        oldL = (oldL==l1 || oldL.substring(0, oldL.indexOf('px'))==(""+l1)) ? l2 : l1;
        eval(fun+"('"+theDiv+"')"+x+"='"+oldL + "px'");
      }
      if(t1) {
        var oldT = eval(fun+"('"+theDiv+"')"+y);
        oldT = (oldT.substring(0, oldT.indexOf('px'))==(""+t1)) ? t2 : t1;
        eval(fun+"('"+theDiv+"')"+y+"='"+oldT + "px'");
      }
    }
}

function MM_showHideLayers() { //v3.0 revised by Clark Lu for switch show and hide
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3)
    if ((obj=MM_findObj(args[i]))!=null) {
      v=args[i+2];
      if (obj.style) {
        obj=obj.style;
        if(!v)
          v=(obj.visibility=="hidden")?"visible":"hidden";
        else
          v=(v=='show')?'visible':(v='hide')?'hidden':v;
      }
      else if(!v)
        v=(obj.visibility=="hide")?"show":"hide";

      obj.visibility=v;
  }
}

function expendCollapseLayers() { // written by Clark Lu
  var i,p,v,obj,args=expendCollapseLayers.arguments;
  for (i=0; i<(args.length-2); i+=3)
    if ((obj=MM_findObj(args[i]))!=null) {
        v=args[i+2];
        if (obj.style) {
            obj=obj.style;
            if(!v)
                v=(obj.display=="none")?"block":"none";
            else
                v=(v=='show')?'block':(v='hide')?'none':v;
        }
        obj.display=v;
    }
}

function isLayerVisible(name) { // written by Clark Lu
  if ((obj=MM_findObj(name))!=null) {
    if (obj.style)
      obj=obj.style;
    return (obj.visibility!="hidden");
  }
  return false;
}

function isLayerExpended(name) { // written by Clark Lu
  if ((obj=MM_findObj(name))!=null) {
    if (obj.style)
      obj=obj.style;
    return (obj.display!="none");
  }
  return false;
}

function switchImage() { // written by Clark Lu
  var i,x,a=switchImage.arguments; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){
   if(srcEquals(x.src, a[i+1])) x.src=a[i+2]; else x.src=a[i+1];}
}

function srcEquals(str1, str2) { // written by Clark Lu
  var endStr1 = str1.substring(str1.lastIndexOf('/'), str1.length);
  var endStr2 = str2.substring(str2.lastIndexOf('/'), str2.length);

  return (endStr1==endStr2);
}

function isDigit(obj) {
    slen=obj.length;
    for (var position=0; position<slen; position++){
        cc = obj.charAt(position);
        if (cc <"0" || cc >"9")
        {
            return false;
        }
    }
    return true;
}

function setEnable(objName, bool) {
  var obj = MM_findObj(objName);
  disable(obj, !bool);
}

function disable() {
  var args=disable.arguments;
  var bool = true;
  if(args.length > 0)
    obj = args[0];
  if(args.length > 1)
    bool = args[1];
  
  if(obj){
    if(obj.type == 'select-one'){
      obj.disabled=bool;
    }else if(obj.length){
      var i;
      for(i=0;i<obj.length;++i)
        obj[i].disabled=bool;
    }else{
      obj.disabled=bool;
    }
  }
}

// added by Clark Lu, 05/29/2003
// checkboxName is the name of checkbox with a form name, such as:
//   document.formName.checkboxName
// the return value is boolean, which is true if at least one checkbox is checked
function isChecked(checkboxName) {
    if( checkboxName == null )
      return false;
    if( !checkboxName.length ) {  // one item
        return checkboxName.checked;
    }
    else {  // muti items
      var i;
      for (i=0; i<checkboxName.length; ++i) {
        if (checkboxName[i].checked)
            return true;
      }
    }

    return false;
}

// added by Clark Lu, 05/29/2003
// 'checkboxName' is the name of checkbox with a form name, such as:
//   document.formName.checkboxName
// 'delimiter' is the delimiter for return String
// the return value is String, include all values which is checked
// such as '232;5345;43534;6456;5333', here ';' is the delimiter
function getAllCheckedValues(checkboxName, delimiter) {
    if( checkboxName == null )
        return null;

    if( !checkboxName.length ) {  // one item
        if( checkboxName.checked )
            return checkboxName.value;
        else
            return null;
    }
    else {  // muti items
        var i, count = 0;
        var skus = '';
        for (i=0; i<checkboxName.length; i++) {
            if (checkboxName[i].checked) {
                if (count > 0)
                    skus = skus + delimiter;

                skus = skus + checkboxName[i].value;
                count++;
            }
        }

        return skus;
    }
}

function setBorderOfEnable(objName, bool) {
  var obj = MM_findObj(objName);
  if (bool)
      obj.style.borderColor = "#404040";
  else
      obj.style.borderColor = "#a0a0a0";
}

function validEMail(objName) {
  var obj = MM_findObj(objName);
  if (!obj)
    return false;

  var val = obj.value;
  if (val.indexOf("@",0) < 0 || val.indexOf(".")<0)
    return false;
  else
     return true;
}

function setFocus(objName, bool) {
  var obj = MM_findObj(objName);

  if (bool) {
    obj.focus();
    obj.select();
  }
  else {
    obj.blur();
  }
}

function clearForm(frm){
  var elements=frm.elements;
  var element;
  var i;
  for(i=0;i<elements.length;++i){
    element=elements[i];
    if(element.type=="text"||element.type=="textarea")
      element.value="";
    else if(element.type=="select-one"||element.type=="select-multiple"){
      var options=element.options,j,item;
      for(j=0;j<options.length;++j){
        item=options[j];
        item.selected=item.defaultSelected;
      }
    }else if(element.type=="checkbox"||element.type=="radio")
      element.checked=element.defaultChecked;
  }
}


//NEC Agent Begin
//Used to format end user price
function roundFloat(value,scale)
{
   var result = 0;
   if(value >= 0)
   {
      val1 = Math.floor(value);
      val2 = Math.round(((value - val1) * Math.pow(10,scale)));
      result = val1 + val2 / Math.pow(10,scale);
   }
   else
   {
      tmpValue = Math.abs(value);
      val1 = Math.floor(tmpValue);
      val2 = Math.round(((tmpValue - val1) * Math.pow(10,scale)));
      result = val1 + val2 / Math.pow(10,scale);
      result = result * -1;
   }

   result="" + result;
   var place = result.indexOf(".");
   if(place >0){
   	var decimal = result.substring(place+1,result.length);
   	if(decimal.length<2)result = result + '0';
   }else{
   	result = result + ".00"
   }
   return result;
   }

function isNumeric(obj) {
    slen=obj.length;
    for (i=0; i<slen; i++){
        cc = obj.charAt(i);
        if ((cc <"0" || cc >"9")&&cc!=".")
        {
            return false;
        }
    }
    return true;
}
function isLoopYear(year)  // added by eric yu
{
	if (year%400 == 0) return true;
	if (year%4==0 && year%100!=0) return true;
	return false;
}
function isValidDate(dateStr)  // added by eric yu
{
    // date format 'mm/dd/yyyy'
    var separator = "/";
    if (dateStr == "") return true;

    for (i=0; i<dateStr.length; i++){
        cc = dateStr.charAt(i);
        if ((cc <"0" || cc >"9") && cc != separator)
        {
            return false;
        }
    }

    var arrayOfStrings = dateStr.split(separator);
    var month = arrayOfStrings[0];
    var day = arrayOfStrings[1];
    var year = arrayOfStrings[2];

    if ( !isDigit(year) ) return false;
    if ( !isDigit(month) || month>12 || month<1) return false;
    if ( !isDigit(day) || day>31 || day<1) return false;
    if (day>30 && (month==4 || month==6 || month==9 || month==11)) return false;
    if (day>29 && month==2 ) return false;
    if (day>28 && month==2 && !isLoopYear(year,month)) return false;
    return true;

}
//NEC Agent End


function deleteXToolsCookies(){
  deleteCookie('c_xTools',contextPath);
  deleteCookie('c_productSearch',contextPath);
  deleteCookie('c_productPnA',contextPath);
  deleteCookie('c_orderSearch',contextPath);
  deleteCookie('c_shopCart',contextPath);
}

function getKeywordCount(chars)
{
    var tmpLength = 0;

    var keywordCount = 0;

    var inQuota = false;
    var newKeywordFlag = true;

	if (chars == null){
		return keywordCount;
	}
    for(i = 0; i < chars.length; i ++)
    {
        var cc = chars.charAt(i);
        if (cc == '"' )
        {
            if (!inQuota)
            {
                inQuota = true;
            }
            else
            {
                inQuota = false;
                tmpLength = 0;
                keywordCount ++;

            }
            newKeywordFlag = true;
        }
        else if (!inQuota && (
                cc == ' '
                || cc == '\n'
                || cc == '\t'
                || cc == '\r'
                || cc == ','
                || cc == ';')
                )
        {
            if (tmpLength > 0)
            {
                tmpLength = 0;
                keywordCount ++;
            }
        }
        else
            tmpLength ++;

    }
    if (tmpLength > 0)
    {
        keywordCount ++;
    }
    return keywordCount;
}

function getKeywordWithQtyCount(chars)
{
    var tmpLength = 0;

    var keywordCount = 0;

    var inQuota = false;
    var newKeywordFlag = true;

	if (chars == null){
		return keywordCount;
	}
    for(i = 0; i < chars.length; i ++)
    {
        var cc = chars.charAt(i);
        if (cc == '"' )
        {
            if (!inQuota)
            {
                inQuota = true;
            }
            else
            {
                inQuota = false;
                tmpLength = 0;
                keywordCount ++;

            }
            newKeywordFlag = true;
        }
        else if (!inQuota && (
                cc == cc == '\n'
                || cc == '\r'
                || cc == ','
                || cc == ';')
                )
        {
            if (tmpLength > 0)
            {
                tmpLength = 0;
                keywordCount ++;
            }
        }
        else
            tmpLength ++;

    }
    if (tmpLength > 0)
    {
        keywordCount ++;
    }
    return keywordCount;
}

//Remove string leading and trailing spaces
//Added by Cheppin, 2004/09/07
function trim(s) 
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}
/* Modify the qtyOnkeypress() to fit the firefox
function qtyOnkeypress() { 
   if ( event.keyCode < 48 || event.keyCode > 57 )
     event.keyCode = 8        
}
*/
function qtyOnkeypress(event) { 
	var key=event.keyCode||event.which;
	if ( key>=48&&key<=57 ||key==8||key==46)
 		return true;
	else
		return false;    
}

/*

IsInt(string,string,int or string):(String,+/- or empty,empty or 0)
*/

function IsInt(objStr,sign,zero)
{
    var reg;    
    var bolzero; 
    if(trim(objStr)=="")
    {
        return false;
    }else{
        objStr=objStr.toString();
    }
    if((sign==null)||(trim(sign)=="")){
        sign="+-";
    }
    if((zero==null)||(trim(zero)=="")){
        bolzero=false;
    }else{
        zero=zero.toString();
        if(zero=="0"){
            bolzero=true;
        }else{
            alert(objStr+" is not a valid integer");
        }
    }
    switch(sign){
        case "+-":
            reg=/(^-?|^\+?)\d+$/;
            break;
        case "+": 
            if(!bolzero){
                reg=/^\+?[0-9]*[1-9][0-9]*$/;
            }else{
                reg=/^\+?[0-9]*[0-9][0-9]*$/;
            }
            break;
        case "-":
            if(!bolzero){
                reg=/^-[0-9]*[1-9][0-9]*$/;
            }else{
                reg=/^-[0-9]*[0-9][0-9]*$/;
            }
            break;
        default:
            alert(objStr+" is not a valid integer");
            return false;
            break;
    }  
    var r=objStr.match(reg);
    if(r==null){
        return false;
    }else{ 
        return true; 
    }
}

function getXMLHTTPObject() {
	var xmlHttpObj = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
        try {
            xmlHttpObj = new XMLHttpRequest();
        } catch(e) {
            xmlHttpObj = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
            xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                xmlHttpObj = false;
            }
        }
    }
    
    return xmlHttpObj;
}

//table sort begin
//<--------------
var compCount = 0;
var swapCount = 0;

function getColumn(o) {
	var cs = document.getElementById("MainTable").rows[0].cells;

	for (var i=0;i < cs.length; i++) {
		if (cs[i] == o.parentNode)
			return i;
	}
	//if not match then return 0
	return 0;
}

function sortTable(id,c,r,tp) {
	var t = document.getElementById(id);
	if (!t)
		return false;

	// The first time this function is called for a given table, set up an
	// array of reverse sort flags.
	if (t.reverseSort == null) {
		t.reverseSort = new Array();
		// Also, assume the team name column is initially sorted.
		t.lastColumn = 1;
	}

	// If this column has not been sorted before, set the initial sort direction.
	if (t.reverseSort[c] == null)
		t.reverseSort[c] = r;

	// If this column was the last one sorted, reverse its sort direction.
	if (c == t.lastColumn)
		t.reverseSort[c] = !t.reverseSort[c];

	// Remember this column as the last one sorted.
	t.lastColumn = c;

	// Set the table display style to "none" - necessary for Netscape 6 
	// browsers.
	
	var theTable = new Array();
	var i;
	for(i=t.rows.length-1;i>=0;i--) 
		theTable[i] = new oRow(getTextValue(t.rows[i].cells[c]),t.rows[i],tp,t.reverseSort[c]);
	
	theTable.sort(compareValues);

	for(i=0;i<theTable.length;i++) 
		t.appendChild(theTable[i].row);

	return false;
}

function oRow (txt,row,tp,rs) {
	this.txt = txt;
	this.row = row;
	this.tp  = tp;
	this.rs  = rs;
}

function compareValues(o1,o2) {
	compCount++;
    
	var v1 = o1.txt;
	var v2 = o2.txt;
	var tp = o1.tp;
	var rs = o1.rs;
    var f1, f2, result;

	// If the values are numeric, convert them to floats.
	if ( tp == 'M' ) {
		/*v1 = v1.replace(/\$|,|\)/g,'');    
		v2 = v2.replace(/\$|,|\)/g,'');  
		v1 = v1.replace(/\(/g,'-');    
		v2 = v2.replace(/\(/g,'-');  */
		v1 = convertCurrency(v1);
		v2 = convertCurrency(v2);
	}

	if ( tp == 'M' || tp == 'N'){  
		f1 = parseFloat(v1);
		f2 = parseFloat(v2);

		v1 = f1;
		v2 = f2;
	}

	if (tp == 'D') {
		if (v1 == null || v1 == "")
			v1 = "1/1/00";
		if (v2 == null || v2 == "")
			v2 = "1/1/00";

		d1 = new Date(v1);
		d2 = new Date(v2);
		
		v1 = d1.valueOf();
		v2 = d2.valueOf();
	}

    // Compare the two values.
	if (v1 < v2)
		result =  -1;
	else if (v1 > v2)
		result =  1
	else 
		result =  0;

	if (rs)
		return -result;
	else 
		return result;
}

function convertCurrency( v ) {
	var m = '',c;
	for ( var i = 0; i < v.length; i ++ ) {
		c = v.charAt(i);
		if ( c == '$' || c == ',' || c == '(' || c == ')') 
		  continue;
		else
		  m += c;
	}
	return m;  
}

function getTextValue(el) {
	if (ie5) {
		return normalizeString(el.innerText);
	}

  // Find and concatenate the values of all text nodes contained within the
  // element.
  var s = "";
  for (var i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);

  return normalizeString(s);
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");
function normalizeString(s) {
  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
  return s;
}
//-------------->
//table sort end......

/*this function is handle that we relace the link <a href="" target="_blank"> to <a href="" rel="external"> for docType */
function externallinks() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a"); 
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href") && 
       anchor.getAttribute("rel") == "external") 
     anchor.target = "_blank"; 
 } 
} 
/*this function is handle that we relace the link <a href="" target="_parent"> to <a href="" rel="parent"> for docType */
function parentlinks() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a"); 
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href") && 
       anchor.getAttribute("rel") == "parent") 
     anchor.target = "_parent"; 
 } 
} 
//if you want to call the DrawImage(this,80,28) in the original version. now you should use <img name="fit_80_28" src="" alt=""> to invoke it.
function fitImage(){
	var imgArr = document.getElementsByTagName("img");
	for(var i=0;i<imgArr.length;i++){
		var name = imgArr[i].name;
		if(name.indexOf("fit_")==0){
			var strArr = name.split("_");
			var width = parseInt(strArr[1]);
			var height = parseInt(strArr[2]);
			fitImageSize(imgArr[i],width,height);
		}
	}
}

function fitImageSize(ImgD,FitWidth,FitHeight){
	var image=new Image();
	if(Browser.IE) image.onerror=function(){image.width=0;image.height=0;}
	image.src=ImgD.src;
	if(image.width>0 && image.height>0){
		if(image.width/image.height>= FitWidth/FitHeight){
			if(image.width>FitWidth){
				ImgD.width=FitWidth;
				ImgD.height=(image.height*FitWidth)/image.width;
			} else{
				ImgD.width=image.width;
				ImgD.height=image.height;
			}
		} else{
			if(image.height>FitHeight){
				ImgD.height=FitHeight;
				ImgD.width=(image.width*FitHeight)/image.height;
			} else{
				ImgD.width=image.width;
				ImgD.height=image.height;
			}
		}
	} 
}

function addWindowEvent(e,f){
	var p = window[e]
	window[e] = (p?(function(){p();f();}):f);
}
addWindowEvent("onload",externallinks);

 //Browser type;
var USER_AGENT = navigator.userAgent;
var Browser={};
Browser.Opera=!!window.opera;
Browser.IE=!!window.ActiveXObject;
Browser.IE6=Browser.IE&&!window.XMLHttpRequest;
Browser.IE8=Browser.IE&&!!document.documentMode;
Browser.IE7=Browser.IE&&!Browser.IE7&&!Browser.IE8;
Browser.IE55=USER_AGENT.indexOf("MSIE 5.5")>=0 && !Browser.IE6 && !Browser.IE7 && !Browser.IE8;
Browser.Firefox=USER_AGENT.indexOf("Firefox/")>=0;
Browser.Firefox2=USER_AGENT.indexOf("Firefox/2")>=0;
Browser.Firefox1=USER_AGENT.indexOf("Firefox/1")>=0

        
 // Hide all select boxes in IE6
function hideSelect(){
        if(Browser.IE6){
            var selectBoxs=document.getElementsByTagName("select");
	        for (var selectIdx=0; selectIdx<selectBoxs.length; selectIdx++)
	        {	            
	          selectBoxs[selectIdx].style.visibility = "hidden"; 	         
            }
        }
}

// Unhide all select boxes in IE6
function unhideSelect(){    
      if(Browser.IE6){	       
	        var selectBoxs=document.getElementsByTagName("select");
	        for (var selectIdx=0; selectIdx<selectBoxs.length; selectIdx++)
	        {	            
	          selectBoxs[selectIdx].style.visibility = "visible"; 	         
            }
        }
}



/**
 *	Whatever:hover - V1.41.050927 - hover & active
 *	------------------------------------------------------------
 *	(c) 2005 - Peter Nederlof
 *	Peterned - http://www.xs4all.nl/~peterned/
 *	License  - http://creativecommons.org/licenses/LGPL/2.1/
 *
 *	Whatever:hover is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	Whatever:hover is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *	Lesser General Public License for more details.
 *
 *	Credits and thanks to:
 *	Arnoud Berendsen, Martin Reurings, Robert Hanson
 *
 *	howto: body { behavior:url("csshover.htc"); }
 *	------------------------------------------------------------
 */

var csshoverReg = /(^|\s)(([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active)/i,
currentSheet, doc = window.document, hoverEvents = [], activators = {
	onhover:{on:'onmouseover', off:'onmouseout'},
	onactive:{on:'onmousedown', off:'onmouseup'}
}

function parseStylesheets() {
	if(!/MSIE (5|6|7)/.test(navigator.userAgent)) return;
	window.attachEvent('onunload', unhookHoverEvents);
	var sheets = doc.styleSheets, l = sheets.length;
	for(var i=0; i<l; i++) 
		parseStylesheet(sheets[i]);
}
	function parseStylesheet(sheet) {
		if(sheet.imports) {
			try {
				var imports = sheet.imports, l = imports.length;
				for(var i=0; i<l; i++) parseStylesheet(sheet.imports[i]);
			} catch(securityException){}
		}

		try {
			var rules = (currentSheet = sheet).rules, l = rules.length;
			for(var j=0; j<l; j++) parseCSSRule(rules[j]);
		} catch(securityException){}
	}

	function parseCSSRule(rule) {
		var select = rule.selectorText, style = rule.style.cssText;
		if(!csshoverReg.test(select) || !style) return;
		
		var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
		var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
		var className = (/\.([a-z0-9_-]*on(hover|active))/i).exec(newSelect)[1];
		var affected = select.replace(/:(hover|active).*$/, '');
		var elements = getElementsBySelect(affected);
		if(elements.length == 0) return;

		currentSheet.addRule(newSelect, style);
		for(var i=0; i<elements.length; i++)
			new HoverElement(elements[i], className, activators[pseudo]);
	}

function HoverElement(node, className, events) {
	if(!node.hovers) node.hovers = {};
	if(node.hovers[className]) return;
	node.hovers[className] = true;
	hookHoverEvent(node, events.on, function() { node.className += ' ' + className; });
	hookHoverEvent(node, events.off, function() { node.className = node.className.replace(new RegExp('\\s+'+className, 'g'),''); });
}
	function hookHoverEvent(node, type, handler) {
		node.attachEvent(type, handler);
		hoverEvents[hoverEvents.length] = { 
			node:node, type:type, handler:handler 
		};
	}

	function unhookHoverEvents() {
		for(var e,i=0; i<hoverEvents.length; i++) {
			e = hoverEvents[i]; 
			e.node.detachEvent(e.type, e.handler);
		}
	}

function getElementsBySelect(rule) {
	var parts, nodes = [doc];
	parts = rule.split(' ');
	for(var i=0; i<parts.length; i++) {
		nodes = getSelectedNodes(parts[i], nodes);
	}	return nodes;
}
	function getSelectedNodes(select, elements) {
		var result, node, nodes = [];
		var identify = (/\#([a-z0-9_-]+)/i).exec(select);
		if(identify) return [doc.getElementById(identify[1])];
		
		var classname = (/\.([a-z0-9_-]+)/i).exec(select);
		var tagName = select.replace(/(\.|\#|\:)[a-z0-9_-]+/i, '');
		var classReg = classname? new RegExp('\\b' + classname[1] + '\\b'):false;
		for(var i=0; i<elements.length; i++) {
			result = tagName? elements[i].all.tags(tagName):elements[i].all; 
			for(var j=0; j<result.length; j++) {
				node = result[j];
				if(classReg && !classReg.test(node.className)) continue;
				nodes[nodes.length] = node;
			}
		}	return nodes;
	}

function fixIE6TextSelectBug(){
document.body.style.height = document.documentElement.scrollHeight + 'px'; 
}
function isValidEMail(email){
    return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email);
}
function trim(str)
{	
  return str.replace(/(^\s*)|(\s*$)/g, ""); 
}
function SearchEvent(){
	//for firefox have no event arguments.
    func=SearchEvent.caller;
    while(func!=null){
        var arg0=func.arguments[0];
        if(arg0 && arg0.constructor){
            return arg0;
        }
        func=func.caller;
    }
    return null;
}
//this is for shopping cart-------------begin------------------
function drawErrorMsg(data,count){
	s = '<div class="errormsg1"></div>';
    s+='<div  class="errormsg2">'
    s+='<span class="errormsg3">Warning!</span>'
    s+='<span class="errormsg3">'+data.notFound +'</span>'
    for( i =0; i < data.errorContents.length; i++){
	    s+='<span>'+data.errorContents[i].itemNotAdded+data.errorContents[i].reason + '</span>'
	}
    s+='</div>'
    return s ;
}
function drawXtoolShoppingCart(data){
	if (!data.parts){
		s = '<div style="margin-top:20px">No Items</div>';
		return s;
	}
	s='<ul>'
	for (i = data.parts.length-1 ; i >=0; i--) {
		s += '<li>'
	    s +='<span class="skuNo">'+data.parts[i].skuNo+'</span>';
	    s +='<span class="qty">'+data.parts[i].qty+'</span>';
		s +='<span class="regprice">'+data.parts[i].price1+'</span>';
	    s +='</li>'
	}
    s +='<ul class="subTotal">'
    s +='<li>Sub-Total:</li>'
    s +='<li>'+data.subTotal+'</li>'
    s +='</ul>'
	return s;
}
function drawInitMsgOfShoppingCart(msg){
	return '<div class="errorMsg" style="clear:both">'+msg+'</div>'
}
function numOnkeypress(event) {
	var key=event.keyCode||event.which;
	if ( key>=48&&key<=57 ||key==8||key==46)
 		return true;
	else
		return false; 
}
function drawParts(part,rowclass){
	s ='<table border="0" cellspacing="0" cellpadding="0" class="menuCartTable ' +rowclass+ '" ><tr>'
	if (part.desc.toString().length>30){
		var newdesc = part.desc.toString().replace(/\'/g,"\\'");
		s+='<td colspan="2"><div class="part_long_desc2"><a href="javascript:viewTechnotes('+ part.skuNo +')" title="'+newdesc+'">' +part.desc.toString().substring(0,30) +'..</a></div></td>';
	}else{
		s+='<td colspan="2"><div class="part_long_desc2"><a href="javascript:viewTechnotes('+ part.skuNo +')">' +part.desc +'</a></div></td>';		
	}

    s+='</tr><tr>';
    s+='<td class="mfgNo">'+part.mfgNo+'</td>'
    //s+='<td class="menuQty">Qty:<input type="text" class="qtyInput" value="'+part.qty+'" onKeyPress="javascript:return numOnkeypress(event)"></td>'
    s+='<td class="menuQty">Qty:'+part.qty+'</td>'
    s+='</tr><tr>';
    s+='<td class="avail">'+part.avail+'</td>'
    s+='<td class="price"><span class="price';
    if(part.saveprice && $.trim(part.saveprice.toString())!=""){
    	s += ' proprice';
    }
    s +=' ">' + part.price1+'</span></td>'
    //s+='<td><div title="Update with 0 qty will delete this item" class="shopUpdate" onclick="updateCarts(\''+ part.POID +'\',$(this).parents(\'table\').find(\'input.qtyInput\').val(),\''+part.itemNo+'\',\'\')"></div></td>'
    //s+='<td class="saveprice">'+part.saveprice+'</td>'
    s+='</tr></table>';
    return s;
};
function fillCartCallBack(data){
	var xtooldata = drawXtoolShoppingCart(data);
	$("#xtoolShoppingCartContent").empty().html(xtooldata);
	var html = ""
	var count = 0;
	if (data.notFound){
		 html += drawErrorMsg(data,count)
		 count ++;
	}	
	if(data.parts){
		for (i = data.parts.length-1 ; i >=0  ; i--) {
			rowclass = i%2==0?"row1":"row2";
	        html += drawParts(data.parts[i],rowclass);
	    }
	    count += data.parts.length;
	}else if (data.initMsg){
		html += drawInitMsgOfShoppingCart(data.initMsg);
		count ++;
	}
	
	//alert(count);
	$("#menuShoppingCartContent").html(html);
	if (count >3){
		$("#menuShoppingCartContent").addClass("shoppingCartItemsGT3");
		$("#menuShoppingCartContent").find("table").addClass("shoppingCartTableGT3");
	}else{
		$("#menuShoppingCartContent").removeClass("shoppingCartItemsGT3");
		$("#menuShoppingCartContent").find("table").removeClass("shoppingCartTableGT3");
	}

	$("#menuShoppingCartItem").text((data.items && data.items!="0")?"CART: "+data.items+" Items: "+ data.subTotal:"No items");
	//if($("#menuShoppingcart").css("display") != "none")
	//	drawShadow4shoppingCart();
	if (count >3){
		var obj = $("#menuShoppingCartContent").get()[0];
		if(obj){
			obj.scrollTop = obj.scrollHeight;
		}
		
		obj = $("#xtoolShoppingCartContent").get()[0];
		if(obj){
			obj.scrollTop = obj.scrollHeight;
		}
	}
}
var openShoppingCartTimeId
var drawShadow4shoppingCart = function(){
		_top = $('#menuShoppingcart').offset().top;
		_left = $('#menuShoppingcart').offset().left;
		_width= $('#menuShoppingcart').width();
		_height= $('#menuShoppingcart').height();
		//alert("top is " + _top + "; left is " + _left + "; width is " + _width  + "; height is " + _height);
		var $dropShadow;
		if ($("div[name='shoppingCartShadow']").size()==0){
	        $dropShadow = $([]);
	        for (var i=0; i < 5; i++) {
	          $dropShadow = $dropShadow.add($('<div></div>').css({zIndex: 3000-i-1, opacity:.1, top: _top + 1+i, left: _left +1+i}));
	        };
	        $dropShadow.attr("name","shoppingCartShadow").css({position: 'absolute', backgroundColor: '#000'}).prependTo("body");
	    }
	    $("div[name='shoppingCartShadow']").css({width:_width+5, height:_height + 5}).show();
}
function openShoppingCart(){
	openShoppingCartTimeId = clearTimeout(openShoppingCartTimeId);
	if ($.fn.bgiframe) { $('#menuShoppingcart').bgiframe(); }
	if($("#menuShoppingCartContent").text().length < 20){
		getECCart();
	}	
	//$('#menuShoppingcart').slideDown('fast',drawShadow4shoppingCart);
	$('#menuShoppingcart').slideDown('slow');
}
function getECCart(){
	var currentURL = window.location.href;
	var isShoppingURL =  (/.*(shopping)|(editPO)+.*/.test(currentURL));
	var $loadingimg = $("#menuShoppingcart .loadingdiv").html();
	$.ajax({
		url :  contextPath + "/order/shoppingCart.do",
		data : {"subAction": 0, "shoppingAction":"quickAdd","isShoppingURL": isShoppingURL},//EditOrderForm.ACTION_quickAdd=6
		type: "GET",
		dataType : "json",
		success: function(data){
			fillCartCallBack(data);
			if(openShoppingCartTimeId == undefined){
				openShoppingCartTimeId = setTimeout("slideUpShoppingCart()",5000);
			}
		},
		error:function(){
			//window.location.href=contextPath;
		},
		beforeSend : function(){
			$("#menuShoppingCartContent").empty().html($loadingimg);
			$("#xtoolShoppingCartContent").empty().html($loadingimg);
			openShoppingCartTimeId = clearTimeout(openShoppingCartTimeId);
		}
	});

}

function addToECCart(options){
	var _data = options.data;
	if (!_data.subAction){
		_data["subAction"]=6;
	}
	if (!_data.quickAddBy){
		_data["quickAddBy"]=2;
	}
	if (!_data.shoppingAction){
		_data["shoppingAction"]="quickAdd";
	}
	var _beforeSend = options.beforeSend;
	var _complete = options.complete;
	var currentURL = window.location.href;
	var $loadingimg = $("#menuShoppingcart .loadingdiv").html();
	if (currentURL && (/.*(shopping)|(editPO)+.*/.test(currentURL)) && typeof(quickAddItems)=='function'){
		$("textarea[name='quickAdd']").val(_data.quickAdd);
		quickAddItems(document.frmPO);
	    return;
	}
	$.ajax({
		url :  contextPath + "/order/shoppingCart.do",
		data : _data,
		dataType : "json",
		type: "POST",
		success: function(data){
			fillCartCallBack(data);
			//openShoppingCart();
		    //invalidate();
		    if(_complete)
			    _complete.call();
		},
		error:function(){
			//window.location.href=contextPath;
		},
		beforeSend : function(){
			$("#menuShoppingCartContent").empty().html($loadingimg);
			$("#xtoolShoppingCartContent").empty().html($loadingimg);
			openShoppingCart();
			openShoppingCartTimeId = clearTimeout(openShoppingCartTimeId);
			if(_beforeSend)
				_beforeSend.call();
		}
	});
}

function updateCarts(){
	var poid = arguments[0];
	var qty= arguments[1];
	var itemno = arguments[2];
	var fromURI = arguments[3];
	var currentURL = window.location.href;
	var $loadingimg = $("#menuShoppingcart .loadingdiv").html();
	if (currentURL && (/.*(shopping)|(editPO)+.*/.test(currentURL))){
		$("input[name='qty" +itemno+ "']").val(qty);
		btnUpdate2Click();
	    return;
	}

	var data = {"poID" :poid,  "itemNos": itemno, "shoppingAction" : "quickAdd","subAction": 20,"fromURI" : fromURI }//EditPOForm.ACTION_updateAndSavePO=20
	data["qty" + itemno] = qty;
	$.ajax({
		url : contextPath + "/order/shoppingCart.do",
		data : data,
		dataType : "json",
		type: "POST",
		success: function(data){
			fillCartCallBack(data);
			if(openShoppingCartTimeId == undefined){
				openShoppingCartTimeId = setTimeout("slideUpShoppingCart()",5000);
			}
		    //openShoppingCart();
		},
		error:function(){
			//window.location.href=contextPath;
		},
		beforeSend : function(){
			$("#menuShoppingCartContent").empty().html($loadingimg);
			$("#xtoolShoppingCartContent").empty().html($loadingimg);
			openShoppingCart();
			openShoppingCartTimeId = clearTimeout(openShoppingCartTimeId);
		}
		
	});

}
function addToLOLCart(options){
	var _data = options.data;
	var param = "";
	$.each( _data, function(key, value){
	    if (key != "shoppingAction"){
		  param += ( key + "=" + value + "&");
		}
	});
	window.location=contextPath + "/order/shoppingCart.do?" + encodeURI(param);
}

function add2Cart(options){ 
    var currentURL = window.location.href;
    var flag=currentURL && (/.*(shopping)|(editPO)+.*/.test(currentURL));
    if(typeof(isGoToCartPage) != 'undefined' && isGoToCartPage !=null && trim(isGoToCartPage)=="" && !flag && ( contextPath=="/ecexpress" || contextPath=="/emj" || contextPath=="/synnexsupply") ){  
		$('#confirmGoToCartPage').modal({
		close:false, 
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer',
		containerCss:{height:'200px'},
		zIndex:2000,
		onShow:function(dialog){
	    	dialog.data.find('.yes').click(function () {
				// call the callback
				var goToCart=$("input[type='radio'][name='isGoToCartPage']:checked").val();		  	
		  		if($('#isSaveToPref').attr("checked")==true){
				    isGoToCartPage=(goToCart=="Y" ? "Y" : "N" );
		            $.ajax({
				      url:contextPath+"/user/setPersonalization.do",
				      type:"post",
				      dataType:"html",
				      data:"isGoToCartPage="+goToCart+"&action=goToCartPage"
				     });
		        }		        
				// close the dialog
				$.modal.close();				
				goToCart=="Y" ? addToLOLCart(options):addToECCart(options);
			});
		}
		});	
   }else{
	if (contextPath=="/ecexpress"){
          if(typeof(isGoToCartPage) != 'undefined' && isGoToCartPage=="Y"){
            addToLOLCart(options);
          }else{
           addToECCart(options); 
          }		
	}else if(contextPath=="/emj"){
	   if(typeof(isGoToCartPage) != 'undefined' && isGoToCartPage=="Y"){
             addToLOLCart(options);
           }else{
            addToECCart(options);
           }
	}else if (contextPath=="/cansupply"){
		     addToLOLCart(options)
	}else if (contextPath=="/rsb"){
		     addToLOLCart(options)
	}else if(contextPath=="/licenseonline"){
		addToLOLCart(options) 
	}else if(contextPath=="/synnexsupply"){
	   if(typeof(isGoToCartPage) != 'undefined' && isGoToCartPage=="Y"){
               addToLOLCart(options);
           }else{
             addToECCart(options);
           }
	}else{
	     if(typeof isGoToCartPage != 'undefined' && isGoToCartPage !=null && isGoToCartPage=="Y" ){
             addToLOLCart(options);
          }else{
            addToECCart(options);
          }
	}
  }
}

function addOneCart2Carts(onecart,_carts){
	isExist = false;
	if (!onecart.qty){
		onecart.qty=1;
	}
	$.each(_carts, function(i,cart){
		if (cart.skuNo == onecart.skuNo){
			isExist = true;
			cart.qty += onecart.qty
		}
	});
	if(!isExist){
		var onecart = {"skuNo":onecart.skuNo, "img":"", "desc":"", "qty":onecart.qty, "price":""};
		_carts.push(onecart);
	}
	//alert(_carts.toJSONString());
	return _carts;

}
	
//this is for shopping cart-------------end--------------------
function initNewXTools(isExpressToolExpand,isGetECCart){
	$('#newXToolsPanel').tabs();
	// init the tabs plug-in	
	initAccordion(isGetECCart);
	var XToolsStatusInCookie=getCookie('xToolsExpandStatus'); //expand/collapse the entire XTools
	var XToolsExpandStatus=true;
        if(typeof XToolsStatusInCookie != 'undefined' && XToolsStatusInCookie !=null){
	    if(XToolsStatusInCookie == 'expand'){
	       XToolsExpandStatus=true;
	       expandXTools();
	    }else if(XToolsStatusInCookie == 'collpase'){
	       XToolsExpandStatus=false;
	       collpaseXTools();
	    }
	}else{
	   XToolsExpandStatus=isExpressToolExpand;
	}
	toggleXTools(XToolsExpandStatus);
}
function initAccordion(isGetECCart){
    var isXToolsAllItemsExpand = getCookie("isXToolsAllItemsExpand");// is auto silding?
	var wizard =$('#tab_xToolsContent').accordion({
		header: '.sectionTitle',
		event: false
	});	
	// init the accordion plug-in and add some seconds delay
	if(typeof isXToolsAllItemsExpand != 'undefined' && isXToolsAllItemsExpand !=null && isXToolsAllItemsExpand == 'autoSliding'){
		$('a.sectionTitle',wizard).each(function(index){
			$(this).hoverIntent({
				sensitivity: 3,
				interval: 200,
				over:function(){
					wizard.accordion("activate", index);
					var date = get30ExpireDateForCookie();
					setCookie('xToolsOpenedIndex', index,date, contextPath);// remember the index of last opened section
					},
				timeout:500,
				out:function(){}});
		}); 
	}
	if(isGetECCart){
		wizard.bind("change.ui-accordion", function(event, ui){
		   if(typeof ui !='undefined'){
			ui.newContent.find("input[type='text']")[0].focus();// auto-focus for input field
			if(ui.newHeader.text().indexOf("Cart")>=0 && $.trim($("#xtoolShoppingCartContent").text()).length < 5){
				getECCart();
			};
		   }
		});
	}
	var openedIndex=getCookie('xToolsOpenedIndex');//open the last opened section	
	if((typeof openedIndex != 'undefined' && openedIndex!=null) 
	     && (typeof isXToolsAllItemsExpand != 'undefined' && isXToolsAllItemsExpand !=null && isXToolsAllItemsExpand == 'autoSliding')){
		openedIndex = (typeof openedIndex == 'string')? parseInt(openedIndex):0;
		wizard.accordion("activate", openedIndex);
	}
}
function destroyAccordion(){
	$("#tab_xToolsContent").accordion("destroy");
	$('a.sectionTitle').each(function(){
  	    $(this).unbind("mouseover");
	    $(this).unbind("mouseout");	
	});
}
function expandXTools(){
	$('#new_img_express_tool').attr("src", url_xtools_expand_img);
	$('#new_img_express_tool_lol').attr("src", url_xtools_expand_img_lol);
	$('#newXToolsPanel,#NewECEContentLeft,#newLOLCSPContentLeft,#toolsWarp').show();
	if($("#newXToolsPanel").activeTab()==2){//if the favorite tab is selected, hide the "autosliding/expand all"
		$('#toolsWarp').hide();
	}
	$('#NewECEContentLeft').css('width','167px');
	setCookie('xToolsExpandStatus', 'expand',null, contextPath);
}
function collpaseXTools(){
	$('#new_img_express_tool').attr("src", url_xtools_collpase_img);
	$('#new_img_express_tool_lol').attr("src", url_xtools_collpase_img_lol);
	$('#newXToolsPanel,#NewECEContentLeft,#newLOLCSPContentLeft,#toolsWarp').hide();
	setCookie('xToolsExpandStatus', 'collpase',null, contextPath);
}
function toggleXTools(isExpand){
   if(isExpand){
	$('.xToolsIndicator').toggle(function(){
	     collpaseXTools();		         
     },function(){
         expandXTools();      
     });
   }else{	    
     $('.xToolsIndicator').toggle(function(){
		expandXTools();        
     },function(){
        collpaseXTools();   
     });
    $('#newXToolsPanel,#toolsWarp').hide(); // hide the express tools on init;
    $('#NewECEContentLeft').css('width','0');
  }
}

function toggleXToolsSection(clickObjID,operateObjID, isCollapse){
 if(isCollapse){
	$('#'+clickObjID).toggle(function(){
	  $(this).attr("src", url_expand_img);
	  $('#'+operateObjID).slideDown();
	},function(){
	  $(this).attr("src", url_collapse_img);
	  $('#'+operateObjID).slideUp();
	}
	);
 }else{
	$('#'+clickObjID).toggle(function(){
	  $(this).attr("src", url_collapse_img);
	  $('#'+operateObjID).slideUp();
	},function(){ 
	  $(this).attr("src", url_expand_img);
	  $('#'+operateObjID).slideDown();
	}
	);
  }
}
function printThisPage(){
  window.print();
}

function get30ExpireDateForCookie(){
	var date = new Date();
	var expireDates = 30;
	date.setTime(date.getTime()+expireDates*24*3600*1000);
	return date;
	
}
function setExpandFavId(objID){
	setCookie("expandFavId",objID,null, contextPath);
}
function getFavDetailDIV(clickObjID,operateObjID, isCollapse){
	if(isCollapse){
		$('#'+clickObjID).attr("src", url_collapse_img);
		$('#'+operateObjID).css("display","none");
	}else{
		$('#'+clickObjID).attr("src", url_expand_img);
		$('#'+operateObjID).css("display","");
	}

}
function checkUSZIP(zip){
	return /^\d{5}(-??\d{4}){0,1}$/.test(zip);
}
function checkCAZIP(zip){
	return /^[A-Za-z]\d[A-Za-z]\s??\d[A-Za-z]\d$/.test(zip);
}
function checkNormalZIP(zip){
	return /^[\dA-Za-z\-\s]*?$/.test(zip);
}
function checkZIP(zip,country){
	if(country == 'US'){
		var flag = checkUSZIP(zip)
		if(!flag){
			alert("Zipcode format is incorrect.\n It should be 99999 or 99999-9999");
		    return false;
		}
	}else if(country == 'CA'){
		var flag = checkCAZIP(zip)
		if(!flag){
			alert("Postal code format is incorrect.\n It should be X9X 9X9 or X9X9X9");
			return false;
		}
	}else {
		var flag = checkNormalZIP(zip);
		if(!flag){
			alert("Zip code format is incorrect");
			return false;
		}
	}
	return true;
}
function setMultiSelectOption(selName,contractsBox,splitChar) {
   obj = MM_findObj(selName);
   splitChar=splitChar?splitChar:"^"
   if(!obj||!contractsBox||contractsBox=="") return;
   contractsBox=contractsBox.split(splitChar);
  
   var options=obj.options;
   var isSelectAll=false;  //set for FireFox Property however ff would select first option
   for(i=0;i<options.length;i++){
      for(j=0 ;j< contractsBox.length;j++){
      	 if(contractsBox[j]==options[0].value) isSelectAll=isSelectAll||true;
    	 if(options[i].value != contractsBox[j]){
    		continue;
    	 }else{
    	    options[i].selected=true;
		 }   
      }
   } 
   options[0].selected=isSelectAll;
}

function isClickedAddToCartImage(event)
{
  var src=(document.all?event.srcElement:event.target);
  if(src.id=='addToCart')
   {
     return false;
   }
  return true;
}

function addToCartWithWH(skuNo, wareHouse,obj){
    var options={};
    var data = {};
    data["quickAdd"] = skuNo;
    data["shoppingAction"]= "quickAdd";
    data["subAction"]     = "6";
    data["quickAddBy"]    = "2";  
    data["wareHouse"]     =wareHouse;   
    var beforeSend = function(){
	$(obj).find("img").attr("src","../images/ajax-loader.gif");
    }
    var complete = function(){
	$(obj).find("img").attr("src","../images/addtocart.gif");
    }
    options["data"] = data;
    options["beforeSend"]= beforeSend
    options["complete"]=complete    
    add2Cart(options);
}

function openPopupOverlay(zIndex){
 	$("<div/>").addClass("popupOverlay").css({
 		"width":$(window).width(),
 		"height":$(window).height(),
 		"z-index":(zIndex)
 	}).appendTo($(document.body)).show();
}
function closePopupOverlay(){
 	$(".popupOverlay").remove();
}

function createKitPartDialog(){
	var kitPartDialog=$("<div>").attr("id","kitPartDialog").css("display","none");
	kitPartDialog.appendTo($(document.body));
	kitPartDialog.dialog({
		bgiframe: true,
		width: 650,
		minHeight: 200,
		modal: false,
		autoOpen:false,
		open:function(event,ui){
			openPopupOverlay($(this).dialog('option','zIndex')-1);
		},
		close:function(event,ui){
			closePopupOverlay();
		}
	});
}

function loadKitPartComponent(techNoteUrl,kitPartUrl,loadingImage,sku,title){
    var kitPartDialog=$("#kitPartDialog");
    kitPartDialog.html("<div  style=\"text-align:center;\"><img src=\""+loadingImage+"\" alt=\"Loding\"></div>");
	if(!(kitPartDialog.dialog("isOpen"))){
			kitPartDialog.dialog('option', 'title', title);
			kitPartDialog.dialog("open") ;
	}
	var d=new Date();
	var dd = d.getMinutes()+"_"+d.getSeconds()+"_"+d.getMilliseconds();
	$.getJSON(kitPartUrl, {skuNo:sku,time:dd}, function(data){
		if(data!=null && data.length>0){
			var resultHtml="<table class=\"availTable\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
			resultHtml+="<th>SKU</th>";
			resultHtml+="<th style=\"line-height:15px\" colspan=\"2\">Component<br>Line# | Qty</th>";
			resultHtml+="<th>MFG#</th>";
			resultHtml+="<th>Price</th>";
			resultHtml+="<th>Avail</th>";
			resultHtml+="<th>Description</th></tr>";
			for(var i=0; i<data.length; i++){
				var part=data[i];
				resultHtml+="<tr>"
				for(var j=0; j<part.length;j++){
					if(j==0){
						resultHtml+="<td><a href=\""+techNoteUrl+part[j]+"\" target=\"_blank\" style=\"color:#333399;\">"+part[j]+"</a></td>";
					}else if(j==4){
						resultHtml+="<td style=\"text-align:right;\">"+part[j]+"</td>";
					}else if(j==6){
						resultHtml+="<td style=\"text-align:left;\">"+part[j]+"</td>";
					}else{
						resultHtml+="<td>"+part[j]+"</td>";
					}
				}
				resultHtml+="</tr>"
			}
			
			resultHtml+="</table>"
		}else{
			resultHtml="There is no component product, please check it latter."
		}
		$("#kitPartDialog").html(resultHtml);
	});
}
function styleadd(e,s){/* change the background-color when mouseover */
	e.mouseover(function(){
	  $(this).addClass(s);
	}).mouseout(function(){
	  e.removeClass(s);
	});
} 


function initTableWidget(objId){//objId is the report engine souce id
	    var obj=$('#'+objId); 
	    if(typeof(obj)=='undefined' || obj==null){// if no report table
	      return ;
	    }
	    var div=$('#'+objId+'_DIV'); 
	    var table=$('#'+objId);
	    if(div.height()>table.height()){// if table height < div height ,adjust the div height to table height.
	      div.height(table.height());
	      return ;
	    }
	    
		$(div).fixedHeaderTable();  // use fixed table header plugin to do
	    $('.fht_table_body').css({"overflow-x":"hidden","overflow-y":"auto"});
	    table.css({"overflow-x":"hidden","overflow-y":"auto","table-layout":"fixed"});
	    
	    //add the previous table attributes to the new table
	    var clsName    =table.attr('class');
	    var cellpadding=table.attr('cellpadding');
	    var cellspacing=table.attr('cellspacing');
	    var border     =table.attr('border');
	    var headerTable=$('.fht_fixed_header > table');
	    if( typeof(clsName) != 'undefined' && clsName!=null){
	       headerTable.addClass(clsName);
	    }
	    if( typeof(cellpadding) != 'undefined' && cellpadding!=null){
	       headerTable.attr('cellpadding',cellpadding);
	    }
	    if( typeof(cellspacing) != 'undefined' && cellspacing!=null){
	       headerTable.attr('cellspacing',cellspacing);
	    }
	    if( typeof(border) != 'undefined' && border!=null){
	       headerTable.attr('border',border);
	    }
	    
	    //add the table fixed footer as bellow:
	    var footer=$('.fht_table_body').clone();
	    footer.find('tbody:first').remove();
	    footer.find('.empty-cell').html('&nbsp;').height(1);
	    div.append(footer);
	    div.height(div.height()+2*$('.foot').height()); 
	    $('.foot:first').parent().remove();   //remove the report engine static row                   
	    $('.fht_table_body:eq(1) > table').css('margin-top','-6px');//hide the footer first row
	    
	    var NewECEContentLeft=$('#NewECEContentLeft');
	    var xToolsHtml=NewECEContentLeft.html();
	    if(typeof(xToolsHtml)!='undefined' && xToolsHtml!=null){ //if current page has xtools area
	        var isDisplayExpressTools=false;
		    var XToolsStatusInCookie=getCookie('xToolsExpandStatus'); //expand/collapse the entire XTools
	        if(typeof XToolsStatusInCookie != 'undefined' && XToolsStatusInCookie !=null && XToolsStatusInCookie == 'expand'){
	            isDisplayExpressTools=true;
	        }
	        var containerDiv=div.parent('td').parent('tr').parent('tbody').parent('table').parent();
	        if(typeof(containerDiv)!='undefined' && containerDiv!=null){
		      var containerWidth=containerDiv.width();
		      if(!isDisplayExpressTools){
		           containerWidth=$(window).width()-NewECEContentLeft.width()-20; 
		      }
		      $('.fht_fixed_header').css('width',containerWidth-20);
		      $('.fht_fixed_header > table').css('width',containerWidth-20);
		      $('.fht_table_body').css('width',containerWidth);
		      $('.fht_table_body > table').css('width',containerWidth-20);
	        }
	        $('#new_img_express_tool').click(function(){
	           window.location.reload();
	        });
	    }
}

/**
 * Initialize top menu, which uses megamenu plugin, in page header
 * Billy Zhou, 2010-11-11
 *
 * @Param menuClass: megamenu's class name
 * @Param tableClass: menu table's class name. Menu contents are wrapped in these tables.
 * @Param menuItemheight: height of each menu item in the menu table
 * @Param options: displaying options for megamenu
 */
function initMegaMenu(menuClass, tableClass, menuItemheight, options) {
	// for IE Explorer
	var isIE = navigator.userAgent.toLowerCase().indexOf('msie') != -1;
	if(isIE)
		menuItemheight++;
	
	// set menu's height and width
	$(tableClass).each(function(i){
		var magaTable = $(this);
		var magaDiv = magaTable.parent();
		var maxItemSize = 0;
		var divWidth = 0;		
		
		// caculate menu item's count and width
		magaTable.find("ul").each(function(i){
			var liItemList = $(this).children("li");
			var curSize = liItemList.length;
			if(curSize > maxItemSize)
				maxItemSize = curSize;	
			
			try{
				var cssWidth = $(this).css("width");
				if(cssWidth != null && cssWidth != 'auto')
					divWidth += parseInt($(this).css("width"));				
			} catch(e) {}			
		});
		
		// set table's height and the div will auto adjust its width to it
		magaTable.height(maxItemSize * menuItemheight);
		
		// set div's width
		ulSize = magaTable.find("ul").size();
		if(divWidth > 0 && ulSize > 0){
			var ulBlanks = 2 * (ulSize-1); // blanks between uls
			var divBlank = 6; // blank between <div> and <table>
			magaDiv.width(divWidth + ulBlanks + divBlank);
		}
		
	});
	
	// call megamenu plugin
	jQuery(menuClass).megamenu(options);
}

function hasXSS(objName) {
	var obj = MM_findObj(objName);
  	if (!obj)
    	return false;
  	var value = obj.value;
  	if(value != null)
  		value = value.toLowerCase();
  	
  	var i = 0;
  	var xss_keyword = new Array();
	xss_keyword[i++] = new RegExp("eval\\((.*)\\)");
	xss_keyword[i++] = new RegExp("<iframe[^>]*>");
	xss_keyword[i++] = new RegExp("javascript:?");
	xss_keyword[i++] = new RegExp("<script[^>]*>");	
	for(i = 0; i < xss_keyword.length; i++) {
		if(xss_keyword[i].test(value)) {
			return true;
		}
	}	
}
function isNumber(value){
	var reg =/^(\+|\-)?(\d)+(\.)?(\d)*$/;
	return reg.test(value);
}
function isDigit(obj) {
    slen=obj.length;
    for (var position=0; position<slen; position++){
        cc = obj.charAt(position);
        if (cc <"0" || cc >"9")	{
            return false;
        }
    }
    return true;
}
/**add by LouLiu**/
function browser(){//browser judgement,when browse is ff or google,return  true
    var firefox=$.browser.mozilla;
    var google = $.browser.safari;
	if(firefox||google){
	return true;
	}
	return false;
}

function chageStyle(obj,top,left){//make the style of page to looks better 
	var txt=obj.text();
	$("#loadedTime").css("padding-top",top);
	$("#loadedTime").css("padding-left",left);
	$("#loadedTime").text(txt);
	obj.text('');
}
/**add by LouLiu end**/

function validatePassword(pwd){
    var pattenChar=/^.*?[A-Z]+.*?$/;
    var pass=false;
    if(pattenChar.test(pwd)){
        pass=true;
    }
    if(!pass){
        return false;
    }
    pass=false;
    var pattenNumber=/^.*?[0-9]+.*?$/;
    if(pattenNumber.test(pwd)){
        pass=true;
    }
    if(!pass){
        return false;
    }
    return true;
}

