var popupid='deliverypopup';

var preinvhist_hid, inventorycode,qtyid,preqty,actionmode,actioncontent,vid;

function checkInventory(vid_in,type,checkedoptionvalue, preinvhist_hid_in, inventorycode_in, qtyid_in,preqty_in,actionmode_in,actioncontent_in)
{
  preinvhist_hid=preinvhist_hid_in;
  inventorycode=inventorycode_in;
  qtyid=qtyid_in;
  preqty=preqty_in;
  actionmode=actionmode_in;
  actioncontent=actioncontent_in;
  vid=vid_in;
  
  var curqty=document.getElementById(qtyid).value;
  if( isNaN(curqty) || curqty.indexOf(".")>-1 )
  {
   closeMenuCancel();
   return false;
  }
  
  var preinvhistid=document.getElementById(preinvhist_hid).value
  var url="deliveryoption.html?vid="+vid+"&type="+type+"&checkedoptionvalue="+checkedoptionvalue+"&preinvhistid="+preinvhistid+"&inventorycode="+inventorycode+"&qty="+curqty;
    
  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 invhistid=root.getElementsByTagName("invhistid")[0].childNodes[0].nodeValue;
   var showpopup=root.getElementsByTagName("showpopup")[0].childNodes[0].nodeValue;
   if(showpopup && showpopup=='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') {
     location.href=actioncontent;
    }
    else if(actionmode=='exec')
     eval(actioncontent);
   }else
   {
    var popupel = document.getElementById(popupid);
    
    var fasterMsg="If you require faster delivery click OK then on the basket specify a required-by date and our staff will contact you with options.";
    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("inventorychanged")[0].childNodes[0].nodeValue;
    var dsmq=root.getElementsByTagName("dropshipminqty")
    var dropshipminqty="";
    if(dsmq && dsmq.length>0)
    	dropshipminqty=dsmq[0].childNodes[0].nodeValue;
    
    var content="<table border='0' width='420px'>";
    var options=genDeliveryOptions(root);
    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+=genOKCancelButtonRow();
    }
    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){
 var content='';
 var options=root.getElementsByTagName("deliveryoption");
 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 genOKCancelButtonRow()
{
 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();'>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();'>Cancel</a></td>"+
            "</tr>"+
           "</table>"+
          "</td>"+
         "</tr>";
  return tmp;
}

function closeMenuCancel() {
	var el = document.getElementById(popupid);
    el.style.visibility = "hidden";
    var qtyfield=document.getElementById(qtyid);
    qtyfield.value=preqty;
}

function closeMenuOK() {
	var el = document.getElementById(popupid);
    el.style.visibility = "hidden";
    var checkedoptionvalue=getCheckedOptionValue();
    checkInventory(vid,'dook',checkedoptionvalue, preinvhist_hid, inventorycode, qtyid,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";
   
}
