var popupid='deliverypopup';

var preinvhist_hid, inventorycode,qtyid,preqty,actionmode,actioncontent,vid,rowcount,itemIndex;

function checkInventorys(itemIndex_in,rowcount_in,vid_in,type,checkedoptionvalue, preinvhist_hid_in,preqty_in,actionmode_in,actioncontent_in)
{
	itemIndex = itemIndex_in;
	rowcount = rowcount_in;
	vid=vid_in;
  preqty=preqty_in;
  actionmode=actionmode_in;
  actioncontent=actioncontent_in;
  preinvhist_hid=preinvhist_hid_in;
  var preinvhistid=document.getElementById(preinvhist_hid).value;
  var url="deliveryoption.html?vid="+vid+"&type="+type+"&checkedoptionvalue="+checkedoptionvalue+"&preinvhistid="+preinvhistid+"&ajax-request=true&count="+rowcount;
  if(itemIndex!=''){
	  var compCodeForOneItem = document.getElementById("compCode_"+itemIndex);
	  var curqtyForOneItem =document.getElementById("qty_"+itemIndex).value;
	  url+="&compCode0="+compCodeForOneItem.value;
	  url+="&qty0="+curqtyForOneItem;
  }else{
	  for(var i=0;i<rowcount;i++){
		  var compCode = document.getElementById("compCode_"+i);
		  var qtyid ="qty_"+i; 
		  var curqty=document.getElementById(qtyid).value;
		  if( isNaN(curqty) || curqty.indexOf(".")>-1)
		  {
		   closeMenuCancel();
		   return false;
		  }else if(curqty>=1){
			  
			  url+="&compCode"+i+"="+compCode.value;
			  url+="&qty"+i+"="+curqty;
		  }
	  }
  }


  url+="&total="+rowcount;
  
  var ajxObj=new net.ContentLoader(url,openMenu,"get","text",null);
}

var messageid="";
function setMessageID(id){
   var messageDest = document.getElementById(messageid);
   if(messageDest) {
    	messageDest.innerHTML = "";
   }
   messageid=id;
}

function getMessageID(){
   return messageid;
}

function openMenu() 
{

   var root=this.req.responseXML.documentElement; //xmlhttp.responseXML.documentElement;
   var itemcount=root.getElementsByTagName("ItemCount")[0].childNodes[0].nodeValue;
   var showpopups =false;
   var index;
   for(var i = 0;i<itemcount;i++){
	   var showpopup=root.getElementsByTagName("showpopup"+i)[0].childNodes[0].nodeValue;
	   if(showpopup && showpopup == 'true'){
		   showpopups = true;
		   index = i;
	   }
   }
   var invhistid=root.getElementsByTagName("invhistid0")[0].childNodes[0].nodeValue;
   var rowcount = root.getElementsByTagName("totalItems")[0].childNodes[0].nodeValue;
   if(showpopups==false)
   {//no need show popup, ordered<instock OR there is ONLY one option
    document.getElementById(preinvhist_hid).value=invhistid; //set invhistid to a hidden field
    //redirect itempage-->basket  catepage-->no  basket-->submit form
    if(actionmode=='redirect') {
    	eval(""+actioncontent+"");
    }
    else if(actionmode=='exec')
     eval("validateBeforeSubmit("+rowcount+")");
   }else
   {
    var popupel = document.getElementById(popupid);
    
    var fasterMsg="If you require faster delivery, please call Customer Service to discuss options and place your order.";
    var firstChooseMsg="Please choose from the following delivery options:";
    var chooseAgainMsg="The inventory level has changed.  Please reselect a delivery option.";
    var outOfStockMsg="Sorry there is not enough stock to fulfill your request.";
    var dropshipMsg="Sorry this item can only be drop shipped but a minimum quantity of {0} must be purchased. Click CANCEL and increase the quantity.";
    
    var inventorychanged=root.getElementsByTagName("inventorychanged0")[0].childNodes[0].nodeValue;
    var dsmq=root.getElementsByTagName("dropshipminqty0")
    var dropshipminqty="";
    if(dsmq && dsmq.length>0)
    	dropshipminqty=dsmq[0].childNodes[0].nodeValue;
    
    var content="<table border='0' width='420px'>";
    var options=genDeliveryOptions(root,index);
    if(options=='')
    {//there is no options
     if(dropshipminqty!="")
      content+=genRedMsgRow(dropshipMsg.replace("{0}",dropshipminqty));
     else
      content+=genRedMsgRow(outOfStockMsg);
     content+=genCancelButtonRow();
    }else
    {
      if(inventorychanged && inventorychanged=='true')
        content+=genRedMsgRow(chooseAgainMsg);
      else
        content+=genRedMsgRow(firstChooseMsg);
      content+=options;
      content+=genMsgRow(fasterMsg);
      content+=genOKCancelButtonRows(rowcount);
    }
    content+="</table>";
    popupel.innerHTML=content;
    
    var center_x=(window.screen.width-popupel.clientWidth)/2 +document.body.parentNode.scrollLeft;
    var center_y=(window.screen.height-popupel.clientHeight-200)/2 + document.body.parentNode.scrollTop;

    popupel.style.left = center_x + "px";
    popupel.style.top  = center_y + "px";
    popupel.style.visibility = "visible";
   }
}


function genDeliveryOptions(root,index){
	 var content='';
	 var options=root.getElementsByTagName("deliveryoption"+index);
	 for(i=0;options && i<options.length;i++)
	 {
	   var optionvalue=options[i].childNodes[0].childNodes[0].nodeValue;
	   var optioncontent=options[i].childNodes[1].childNodes[0].nodeValue;
	   content+=genOptionRow(optionvalue,optioncontent);
	 }
	 return content;
	}

function genRedMsgRow(msg)
{
  var tmp="<tr>"+
    		"<td>&nbsp;&nbsp;</td>"+
            "<td align='left' class='popup_menuItem_red'>"+msg+"</td>"+
           "</tr>";
  return tmp;
}

function genMsgRow(msg)
{
  var tmp="<tr>"+
    		"<td>&nbsp;&nbsp;</td>"+
            "<td align='left' class='popup_menuItem'>"+msg+"</td>"+
           "</tr>";
  return tmp;
}

function genOptionRow(optionvalue,optioncontent)
{
 var tmp="<tr>"+
           "<td><input name='deliveryoption' value='"+optionvalue+"' type='radio'></td>"+
           "<td align='left' class='popup_menuItem'>"+optioncontent+"</td>"+
         "</tr>";
 return tmp;
}

function genOKCancelButtonRows(rowcount)
{
 var tmp="<tr>"+
          "<td>&nbsp;</td>"+
          "<td align='center'>"+
           "<table border='0' width='50%'>"+
            "<tr>"+
       	 	  "<td width='50%' align='center'><a href='javascript:void(0);' class='popup_menuItem' onClick='if(getCheckedOptionValue()==-1){alert(\"please check an option.\");} else { closeMenuOK(); } '>OK</a></td>"+
    	      "<td width='50%' align='center'><a href='javascript:void(0);' class='popup_menuItem' onClick='closeMenuCancel("+rowcount+");'>Cancel</a></td>"+
            "</tr>"+
           "</table>"+
          "</td>"+
         "</tr>";
  return tmp;
}

function genCancelButtonRow()
{
 var tmp="<tr>"+
          "<td>&nbsp;</td>"+
          "<td align='center'>"+
           "<table border='0' width='50%'>"+
            "<tr>"+
    	      "<td width='50%' align='center'><a href='javascript:void(0);' class='popup_menuItem' onClick='closeMenuCancel("+rowcount+");'>Cancel</a></td>"+
            "</tr>"+
           "</table>"+
          "</td>"+
         "</tr>";
  return tmp;
}


function closeMenuCancel(rowcount) {
	var el = document.getElementById(popupid);
	 el.style.visibility = "hidden";
	 if(itemIndex!=''){
		 var qtyfieldForOne=document.getElementById("qty_"+itemIndex);
		 qtyfieldForOne.value=preqty;
	 }else{
		 for(var i = 0;i<rowcount;i++){
			 var qtyfield=document.getElementById("qty_"+i);
		 	if(qtyfield){
			 qtyfield.value=preqty;
		 	}
		 } 
	 }
	 
}

function closeMenuOK() {
	var el = document.getElementById(popupid);
    el.style.visibility = "hidden";
    var checkedoptionvalue=getCheckedOptionValue();
    checkInventorys(itemIndex,rowcount,vid,'dooks',checkedoptionvalue, preinvhist_hid, preqty,actionmode,actioncontent)
}

function getCheckedOptionValue()
{
  var alloptions=document.getElementsByName("deliveryoption");
  for(i=0;i<alloptions.length;i++)
  {
    var tmp=alloptions[i];
    if(tmp.checked)
     return tmp.value;
  }
  
  return -1;
}

function makeCompCode( itemCode )
{

    var attr = getAttributeOption( "basketItems[0].attributes" );

    return attr!=""?itemCode+"."+attr:itemCode;

}


function getAttributeOption(matchstr )
{
	var selectArray = document.getElementsByTagName('select');
	var options ="";
	for(var i=0; i<selectArray.length; i++) {
		var selectAttr = selectArray[i];
		if (selectAttr && beginWith(selectAttr.name, matchstr)) {
			options += selectAttr.options[selectAttr.selectedIndex].title;
			options += "-";
		}
	}
	
	options = options.substring(0, options.length-1);

	return options;
}

function beginWith( sourcestr, matchstr )
{
    var index = sourcestr.indexOf( matchstr );
    
    if( index == 0 )
        return true;
    else
        return false;
}

function calcShipCost(vid,frm)
{    
  var countryid = frm.countryid.value;
  var provinceid = frm.provinceid.value;
  var city = frm.city.value;
  var postal = frm.postal.value;
  var ordertype = "undefined";
  /*
  var el = frm.elements["orderType"];
   for(var i=0;i<el.length;i++){
     if(el[i].type=="radio" && el[i].checked==true){
     	ordertype = el[i].value;
     }
   }
  
  if( ordertype=="undefined" || (ordertype!="B" && ordertype!="P") )
  {
   alert("Please choose order type!");   
   return false;
  }
  */
  if( countryid=="undefined" || countryid<=0 )
  {
   alert("Please select country!");   
   return false;
  }
  if( provinceid=="undefined" || provinceid<=0 )
  {
   alert("Please select province!");   
   return false;
  }
  if( city=="undefined" || city=="" )
  {
   alert("Please input city!");   
   return false;
  }
  if( postal=="undefined" || postal=="" )
  {
   alert("Please input postal/zip!");   
   return false;
  }
  
 
  var url="calcshipcost.html?vid="+vid+"&ordertype="+ordertype+"&countryid="+countryid+"&provinceid="+provinceid+"&city="+city+"&postal="+postal;
    
  var ajxObj=new net.ContentLoader(url,showPriceMsg,"get","text",null);
}

function showPriceMsg() 
{

   var root=this.req.responseXML.documentElement; //xmlhttp.responseXML.documentElement;
   var errmsg = root.getElementsByTagName("error")[0].textContent;
   
   var shipcost=root.getElementsByTagName("shipcost")[0];
   var haserror=root.getElementsByTagName("haserror")[0].textContent;
   
    var popupel = document.getElementById(popupid);
    
   
    var Msg="<ul>";
    var costes = shipcost.getElementsByTagName("cost");
    for(var i=0;i<costes.length;i++){
       var cost = costes[i];
       Msg = Msg +"<li>"+cost.firstChild.textContent+" : $"+cost.lastChild.textContent+"</li>";
    }
    Msg = Msg +"</ul>";
    if(haserror=="false")  
       Msg = errmsg;
    var content="<table border='0' width='420px'>";
  
     content+=genRedMsgRow(Msg);
     content+=genPriceOkButtonRow();
    
    content+="</table>";
    popupel.innerHTML=content;
    
    var center_x=(window.screen.width-popupel.clientWidth)/2 +document.body.parentNode.scrollLeft;
    var center_y=(window.screen.height-popupel.clientHeight-200)/2 + document.body.parentNode.scrollTop;

    popupel.style.left = center_x + "px";
    popupel.style.top  = center_y + "px";
    popupel.style.visibility = "visible";
  
}

function genPriceOkButtonRow()
{
 var tmp="<tr>"+
          "<td>&nbsp;</td>"+
          "<td align='center'>"+
           "<table border='0' width='50%'>"+
            "<tr>"+
    	      "<td width='50%' align='center'><a href='javascript:void(0);' class='popup_menuItem' onClick='closePriceOk();'>OK</a></td>"+
            "</tr>"+
           "</table>"+
          "</td>"+
         "</tr>";
  return tmp;
}

function closePriceOk() {
	var el = document.getElementById(popupid);
    el.style.visibility = "hidden";
   
}

