/*
   This screen displays the product info. This includes e-content from appropriate vendors
   as well as pricing information based on matrix
   
   For a search by keyword or by category, it gives a resulting product list
   
   For a single SKU it shows base content for that product along with
   all technical and marketing info etc
   
   The top half shows basic information and an image
   
   The bottom half has "tabs" which control the display of:
   a) All detailed product information
   b) Any accessories
   c) Any upsell items ("Others to Consider")
   d) Any similar products
   
   Clicking on a tab makes it visible and scrolls to where the item displayed is at
   the top of the window
   
   The whole point is to allow the customer to add items
   to the shopping cart
   
   This can be done 2 ways:
   
   1) On base product display they can click "Add this item to cart"
   2) On the various product lists (search results, or for single product, the
      accessories, upsell and similar products)
      
    They can select multiple items on any list and click "add to cart" and
    they will all be added.
    
    If, while on the list they want to see the full detail for that item they
    click on the product description and this will launch the base content product
    display
    
    If they click on the image (either on a list or on the base content display) they
    will see a larger image displayed
    
    The shopping cart data is maintained by a PHP program which this screen (via Javascript)
    links to asynchronously as a requirement is that the dealer can see who is on-line
    shopping and what is in their cart at the time. As a result, in additon to PHP keeping it in the
    session variable, it is also in a MySQL table that they can browse while the session is occurring
    
    The Javascript simply passed it a table of items to be added/replaced in the cart. PHP also
    returns a summary lof number of items and total dollar value for items currently in the cart
*/
//
var cartContents = new Array();
var cartItems = new Array();
var globalFunc = "";

window.onload = prodSetUp;
//
//      set up event handler and initiate timer
//
function prodSetUp () {
//    document.getElementById("skuIn").onblur = getProductList;
    if ($("submit_get_single_sku")) {
        $("submit_get_single_sku").onclick = getSingleSKU;
    }
    if ($("submit_getproduct")) {
        $("submit_getproduct").onclick = getProductList;
    }
//
//   clear out form input fields
//
    if ($("skuIn")) {
        $("skuIn").value = "";
    }
    if ($("requestIn")) {
        $("requestIn").value = "";
    }
    
    //displaySummary();
}
//
//     this function is invoked when page is loaded
//     it calls PHP function that maintains the current
//     shopping cart and it's contents
//
//     the default is to show only a summary of the contents
//     of the cart (# items, total value) or show "cart is empty"
//     if no items.
//
//     then, if cart has items, display a link to click to "View cart"
//
//     this PHP function returns an array of data as follows
//
//     cartContents = new Array("items"=>"0",
//                               "sub_totals"=>"0",
//                               "details"=>"")
//
//     the PHP is passed a function type as follows:
//
//     function             meaning
//
//     "summ"               prodvide only summary totals for cart
//     "display"            provide all data to diaplay cart
//     "add"                add these items to cart (passed in an array of SKU and quantity
//                          if PHP finds item already in cart, it overlays it with the passed
//                          quantity, otherwise it adds it. In any case update cart totals
//     "del"                delete/remove item from cart and update all totals
//
//     when adding or deleting items it is also passed an array of the item SKU's and their
//     quantity selected
//
//     if the result of the operation is that there are no items in the cart, it will simply
//     return "items"=>"0" and this program will show "your cart is empty"

function displaySummary() {
    getCart("summ",cartItems);
}
function viewCart() {
    getCart("display",cartItems);
//    $("shopcart").innerHTML = cartContents['details'];
    $("shopcart").style.display = "block";
    
}
//
//    this is a stub for the PHP program that will really do this function
//

function getCart(action,cartItems) {
    getCartPHP(action,cartItems);
}
//
//     now actually do the http request to shop_cart.php
//
function getCartPHP(action,cartItems) {
//
//   format the request in "POST" method format
//
//    no longer send "action" as a post variable, instead, a different
//    php program will be called based on what function is requested
//
//    so the call to getPHP will send different php program name
//    based on the value of "action
//
//    postData = "action=" + action;
//
    var postData = "";
    var outId;
    if (action == "summ" || action == "add") {
        outId = "summary_div"
    }
    else {
        outId = "output_div" 
    }
//
//   for add, format post data items to include the
//   items being added to the cart. Formatted as an array as follows:
//   'cart_items[' + i + ']["sku"]=' + sku + '&cart_items[' + i + ']["qty"]=' + qty 
//
    if (action == "add") {
        for(var i=0;i<cartItems.length;i++) {
           postData += '&data[' + i + '][qty]=' + cartItems[i]["qty"] + '&data[' + i + '][sku]=' + cartItems[i]["sku"];
        }
    }

	//  similarly for add to favorites	
	if (action == "fav") {
        for(var i=0;i<cartItems.length;i++) {
           postData += '&data[' + i + '][qty]=' + cartItems[i]["qty"] + '&data[' + i + '][sku]=' + cartItems[i]["sku"];
        }
    }
	
	if (action == "rem_cart") {
        for(var i=0;i<cartItems.length;i++) {
           postData += '&data[' + i + '][val]=' + cartItems[i]["val"];
        }	
    }
	
	if (action == "rem_all_cart") {
           postData = '&data=' + 'rem_all';
    }
	
	if (action == "rem_all_fav") {
           postData = '&data=' + 'rem_all';
    }
	
	if (action == "set_checkout_data") {
		   data=cartItems.split('/');
           postData = '&comment=' + data[1]+'&purch_order=' + data[0];
	}
	
	if (action == "set_purchase_order") {
           postData = '&purch_order=' + cartItems;
	}
	
	if (action == "set_comment") {
           postData = '&comment=' + cartItems;
	}
	
	if (action == "rem_fav") {
        for(var i=0;i<cartItems.length;i++) {
           postData += '&data[' + i + '][val]=' + cartItems[i]["val"];
        }
	}	
	
    if (action == "summ") {
      getPHP("/aos/cart/php/route_request.php?request=show_cart",postData,outId);
    }
	else if (action == "fav") {
      getPHP("/aos/cart/php/route_request.php?request=add_favorites",postData,'');
    }
	else if (action == "rem_cart") {
	    getPHP("/aos/cart/php/route_request.php?request=cart_remove_item",postData);
    }
	else if (action == "rem_all_cart") {
      getPHP("/aos/cart/php/route_request.php?request=cart_remove_item",postData);
    }
	else if (action == "rem_all_fav") {
      getPHP("/aos/cart/php/route_request.php?request=remove_favorite",postData);
    }
	else if (action == "rem_fav") {
	    getPHP("/aos/cart/php/route_request.php?request=remove_favorite",postData);
		postData += '&icount=1';
	}
	else if (action == "set_checkout_data") {
	    getPHP("/aos/cart/php/route_request.php?request=checkout_data",postData);
	}
	else if (action == "set_purchase_order") {
	    getPHP("/aos/cart/php/route_request.php?request=set_purchase_order",postData);
	}
	else if (action == "set_comment") {
	    getPHP("/aos/cart/php/route_request.php?request=set_comment",postData);
	}		
    else { 
		getPHP("/aos/cart/php/route_request.php?request=cart_add_item",postData,outId);
		getPHP("/aos/cart/php/route_request.php?request=cart_recalc",'icount=1',"item_count");
		getPHP("/aos/cart/php/route_request.php?request=cart_recalc",'icount=2',"total_count");
		
		if ($('quickViewSkuAdd_'+cartItems[0]["sku"])) {
			$('quickViewSkuAdd_'+cartItems[0]["sku"]).innerHTML="The following items were added to cart: " + cartItems[0]["sku"];
			$('quickViewSkuAdd_'+cartItems[0]["sku"]).style.display='block';
		}
    }
}
//
// this function is invoked when the quantity field of a given line item is
// changed
//
// it's purpose is to automatically take that to mean the customer is selecting
// that item, so save them the trouble and check the selection box for them (if it was not already
//  selected) and highlight the line, so then all they need to do is click on "add items to cart"
//
//  if they are "blanking out" the quantity, do the reverse
//
// it is passed the id (the SKU) of the item being changed
// this is the id of the parent <tr> in the table so is used to highlight
// by adding css class to that item
//
//  the checkbox for this item has an id = "s" + SKU number as it's format
//
//when qty updates function highlights item and show selected.
//when qty is 0 highlight off and item unselected.
//
function updateQty(id) {
    if ($("q" + id).value == "") {
        $("s" + id).checked = 0;
        $(id).className = $(id).className.replace(" highlight","");
    }
    else {
//
//     first check to see if item already checked and highlighted
//
        if ($("s" + id).checked == 0) {
			if($('q'+id).value > 0){
				$("s" + id).checked = 1;
				$(id).className= "highlight";
			}
        }
		
		if($('q'+id).value == 0){
			$("s" + id).checked = 0;
			$(id).className='';
		}
    }
}
//
//     this function sets the display attribute for
//     divs at the bottom of the screen to show or hide them
//     the onclick attribute on the <a> tag passes an argument of
//     the div id that the link that was clicked controls (var divid)
//
function displayTab(divid) {
//
//       first set all four divs to display:none
//       then simply turn on the one that was clicked
//       to display:block
//
      var dispValue1 = "none";
      //var dispValue2 = "none";
      var dispValue3 = "none";
     // var dispValue4 = "none";
//
//    now set the one to "block" which was clicked
//
      switch(divid) {
        case "details" :
            dispValue1 = "block";
            break;
        case "accessories" :
            dispValue2 = "block";
            break;
        case "upsell" :
            dispValue3 = "block";
            break;
        case "similar" :
            dispValue4 = "block";
            break;
        default :
            dispValue1 = "block";
      }
//
//        div id="details" always exists but the others are optional
//        check to see if they exist before setting display attribute
//
            $("details").style.display = dispValue1;
            if ($("upsell") != null) {  
                $("upsell").style.display = dispValue3;
            }
			/*
            if ($("accessories") != null) { 
                $("accessories").style.display = dispValue2;
            }			
            if ($("similar") != null) {  
                $("similar").style.display = dispValue4;
            }
			*/
//
//        finally, move the tab just selected to top of window.
//        Scriptaculous Effect.ScrollTp function moves the id you pass it to
//        the top of the screen. Id 'prodtabs' is the id of the div just before the
//        tabs at bottom of screen. So when any tab is clicked it moves the bottom
//        half of the screen to the top of the window in a duration of 0.3 seconds
//        (which can be chnaged by changing this parameter passed to the function)
//
       new Effect.ScrollTo('prodtabs',{duration:'0.3'});
       return true;
}

//
//on click of more button accessories will display in full page hidding other informations
//
function assc_more() {
	$('details').style.display='none';
	$('short_detail').style.display='none';
	$('tabs').style.display='none';
	$('accessories_sort').style.display='none';
	$('accessories').style.display='block';
}

function assc_back() {
	$('details').style.display='block';
	$('short_detail').style.display='block';
	$('tabs').style.display='block';
	$('accessories').style.display='none';
	$('accessories_sort').style.display='block';
}
//set comment and purchase order number when user check out from cart deatil page
function get_checkout_data(){
	var comment;
	var purch_order;
	purch_order=$('purchase_order').value;
	comment=$('check_out_comment').value;
	str=purch_order+'/'+comment;
	getCart('set_checkout_data',str);
}
//update session on blur purchase order
function set_purchase_order(){
	var purch_order;
	purch_order=$('purchase_order').value;
	getCart('set_purchase_order',purch_order);
}
//update session for comments
function set_comment(){
	var comment;
	comment=$('check_out_comment').value;
	getCart('set_comment',comment);
}
//
//
//
function check_fav() {
	//if($('topDivOnFavorite') || $('short_detail') || $('show_cart') || $('checkout_show_cart')){
		//$('sidebar').style.display='none';
	//}
}

//
//      this function uses AJAX to invoke a php function,
//      passes it the input fields on the screen and outputs
//      the results of this function which re-displays what was
//      input in a separate div on the screen
//
function getSingleSKU(singleSKU,skuType) {
//     alert("# args = " + arguments.length);
//     alert("singleSKU= " + singleSKU + " skuType = " + skuType);
//
//   initialize output area and collect up all <input> tags
//
//
//   this function can be invoked by directly entering an SKU
//   on the screen or by clicking a product in the product list display
//
//   if it was from product list display (you can tell as the SKU came from
//   input params and not from screen), then format a "Back to Search Results"
//   link for the resulting individual base product display (so user can
//   return to last list after viewing that prtoduct)
//
//   This is needed as back bar is not functional since we are using Ajax
//   to show new screen content
//
	if ($("searchfilter")) {
		$("searchfilter").style.display='none';
	}
	
	if ($("filter")) {
		$("filter").style.display='none';
		$("filterContent").style.display='none';
	}
	
	if ($("search_count")) {
		$("search_count").style.display='none';
	}
	
    var request = "";
    var requestType = "";
//
//   if only 1 argument, then it is event object so
//   use screen input field instead
//
    if (arguments.length == 0 || arguments.length == 1) {
        request = $("skuIn").value;
    }
//
//   if 2 arguments, this means it was called by button click
//   of an item in the product list, so take the input
//   from the params passed and also format the "Back to Search" button
//   so user can get back to search after viewing this individual
//   product
//
    if (arguments.length == 2) {
        request = singleSKU;
        requestType = skuType;
        formatBackButton();
    }

//
//  check to make sure something was entered either
//  in input or by passed parameter
//
    if (request == " " || request == "") {
        $("skuIn").value = "Required";
        $("skuIn").className += " invalid";
        return false;
    }
    else {
		 if ($("skuIn")) {
			$("skuIn").className = $("skuIn").className.replace(" invalid","");
		 }
		
    }
//
    var postData = "";
//
//     generalized routine loops through all input fields
//     getting the name and value and creates a string
//     for the "POST" request to send to PHP function
//
//     only do this if the <input> tag has a name attribute
//     this is checked to avoid sending things like the "submit" button
//     which is also an <input> tag
//
//     after the first name/value pair is constructed, put "&" between
//     each value as required in "POST" data format
//
//
//     specifically pass the value of "data_source" which is an input type=hidden value
//     on the form which indicates if the product data comdes from etilize (SPRLIVE)
//     or our own database (LOCAL)
//
    if ($("skuIn")) {
		var postName = $("skuIn").name;
	} else {
		var postName = "request";
	}

    postData = postName + "=" + request + "&method=getProduct&skuNumberType=" + requestType;
    postData += "&data_source=" + $("data_source").value;
//    alert("Formatted postData = " + postData);
//
//    now launch PHP function
//
    //$("output_div").innerHTML = "";
    //getPHP("/aos/modules/search/get_prod.php",postData,"output_div");
     
}
function formatBackButton() {
    var prev = "prevpage";
	if ($("backButton")) {
		$("backButton").innerHTML = '<form name="back_to_search_form" method="post"><input type="button" value="Back to Search" onclick="getProductList(\''+prev+'\');displayOff(\'1\');"></input></form>';
		
	}
}
//
//        can be called with func as follows"
//        prev = perform previous saved search (back to search results)
//        del =  delete specified search criteria and re-do search
//        if func = del then  var "filter" is the search argument to delete
//

function getProductList(e,func,filter) {
//	alert("this object tag name = " + this.tagName);
//
//     alert("# args = " + arguments.length);
//     alert("e = " + e + " func= " + func + " filter = " + filter);
//  
//   initialize output area and collect up all <input> tags
//   also initialize "Back to Search Results" so it doesn't appear
//   as it only appears on single product display that came from selecting
//   an item on a product list
//
//   check radio button to see whether this is a new search or and "add to search"
//
    var searchType = "new";
	
	if (e.id == "submit_getproduct" || e.id == "form_getproduct") {
		$("add_search").value='new';
		setCookie('search_type','new','1');
	}
	else if (e.id == "category" || e.id == "form_getcategory") {
		$("add_search").value='cat';
		searchType = getCookie('search_type');
	}
	else if (e.id == "manufacturer" || e.id == "form_getcategory") {
		$("add_search").value='man';
		searchType = getCookie('search_type');
	}
	else if (e.id == "result_per_page") {
		$("add_search").value='result_per_page';
		searchType = getCookie('search_type');
	}
	else if (e.id == "sort_by") {
		$("add_search").value='sort_by';
		searchType = getCookie('search_type');
	}
	
	/*
	if ($("addsearch")) {
		if ($("addsearch").checked == 1) {
			searchType = "add";
		}
	}
	*/

	if ($("backButton")) {
		$("backButton").innerHTML = "";
	}
	
	/*
    var request = " ";
	if ($("requestIn")) {
		request = $("requestIn").value;
	}
	*/

	var filterType="";
	
	if (typeof(func) != "undefined") {
	filterType = func.substring(func.indexOf('_')+1, func.length);
	func = func.substring(0, func.indexOf('_'));
	}
	else {
	filterType = "";
	}
                	
    var type = " ";
	if ($("add_search")) {
		if (filterType == "new")
		type = filterType;
		else
		type = $("add_search").value;
	}

	if ($("new_search")) {
		if ((type == "cat" || type == "man") && func != "del") {
			searchType = $("new_search").value;
			request = "x";
		}
		else if (type == "result_per_page" || type == "sort_by") {
			request = getCookie('request');
		}
	}	
	
//
//  check to make sure something was entered either
//  in input or by passed parameter or a prev search was requested
//  by clicking "Batck to Search Results (value of "prev')
//
//
    if(arguments.length = 1){
        if(typeof(e) == 'string') {
            func = e;
        }
    }

	if (typeof(func) == 'string') {
		if (func.substring(0,4) == "move" || func == "nextpage" || func == "prevpage") {
			type = "";
		}	
	}
//
//    if this is not an "Back to Search Results", a "delete from search" or
//    a request for another page number, then this field (request) is required)
//
    if (typeof(func) == "undefined") {
        if (request == " " || request == "") {
            $("requestIn").value = "Required";
            $("requestIn").className += " invalid";
            return false;
        }
        else {
            $("requestIn").className = $("requestIn").className.replace(" invalid","");
        }
    }

	//forwardURL();
//
//   now determine if you are doing a new search or re-issuing the previous
//   one (based on input arg prev)
//
//   if issuing a new one, save the current parammeters(request, pageNo, pageSize)
//   in cookies for later possible use.
//
//   if re-issuing the previous one, retrieve these vales from previous stored
//   cookies and use them to launch the PHP to satisfy the request
//
//
//  if adding to search, you get the existing cookie, append the part being added
//  (delimited by "|" to make each part deleteable later), save the new request
//   in the cookie (for later use in a "prev" request) and then format the request
//
//  since this is basically a new request and you do not know how many pages will be generated
//  (as list is likely to be reduced in size), set pageNo to 1 so they get the new seach from the beginning
//
	if(searchType == "add") {
		if ($("category") && type == "cat") {
			request = $("category").value;
			request = request.replace(","," ");
			
			$("category_text").style.display = 'none';
			$("category_select").style.display = 'none';
			
			if ($("manufacturer_text").style.display == 'none')
				$("searchfilter").style.display='none';
		}

		if ($("manufacturer") && type == "man") {
			request = $("manufacturer").value;
			request = request.replace(","," ");
			
			$("manufacturer_text").style.display = 'none';
			$("manufacturer_select").style.display = 'none';

			if ($("category_text").style.display == 'none')
				$("searchfilter").style.display='none';			
		}		
        
        var oldRequest = getCookie('request');
		var oldType = getCookie('addtype');
		
			if (oldRequest.indexOf("|") >=0 && oldType == type) {
				oldRequest = oldRequest.substring(0, oldRequest.indexOf("|"));
				oldType = type;
			}
		
			if (func == "nextpage" || func == "prevpage") {
				request = getCookie('request');
			}
			else {
				var newRequest = oldRequest + "|" + escape(request);
				setCookie('request',newRequest,'1');
				request = newRequest;
			}
			
	
			if (func == "nextpage" || func == "prevpage") {
				type = getCookie('addtype');
			}
			else {
				var newType = oldType + "|" + type;
				setCookie('addtype',newType,'1');
				type = newType;
			}
    }
	else if ((searchType == "new" || searchType == "cat") && type == "result_per_page" && func != "del") {
		pageSize = $("result_per_page").value;
	}
	else if ((searchType == "new" || searchType == "cat") && type == "sort_by" && func != "del") {
		sortBy = $("sort_by").value;
	}	
    else {
        if (func) {
            if (func == "prev" || func == "previous") {
                request = getCookie('request');
            }
            else {
				if (func == "del") {
                    var oldRequest = getCookie('request');
					oldRequest = unescape(oldRequest);
					
					var newRequest = "";
					
						if (oldRequest.indexOf('|') >=0)
							newRequest = oldRequest.replace("|"+filter,"");
						else
							newRequest = oldRequest.replace(filter,"");
							
                        setCookie('request',newRequest,'1');
                        request = newRequest;
						
					var oldType = getCookie('addtype');	
					var newType = "";
						if (oldType.indexOf('|') >=0)
							newType = oldType.replace("|"+filterType,"");
						else
							newType = oldType.replace(filterType,"");
							
						setCookie('addtype',newType,'1');
						type = newType;
                }
                else {
                    if (func == "nextpage" || func == "prevpage" || func.substring(0,4) == "move") {
                        request = getCookie('request');
						searchType = getCookie('search_type');
						if ($("result_per_page"))
						pageSize = $("result_per_page").value;
						else
						pageSize = 10;
                    }
                    else {
                        alert("Error in passed parameter to function getProductList. func = " + func + ". # args = " + arguments.length);
                    }
                }    
            }
        }
        else {
            setCookie('request',request,'1');
			setCookie('addtype',type,'1');
        }
    }
//
//
//    now that you have request located from whatever source (cookie, screen)
//    replace any "|" delimiters that might be there before formatting
//    the request to send. A space is used instead as etilize recognizes as
//    space between search ketywords to mean "AND" (a comma means "OR")
//    since function replace() only does the first one it sees, you must loop
//    through the request until you find no more instances of that string
//
      var delimMatch = request.indexOf("|");
      while(delimMatch != -1) {  
            request = request.replace("|", ",");
            delimMatch = request.indexOf("|");
      }
//
//    var postData = "";
//
//     generalized routine loops through all input fields
//     getting the name and value and creates a string
//     for the "POST" request to send to PHP function
//
//     only do this if the <input> tag has a name attribute
//     this is checked to avoid sending things like the "submit" button
//     which is also an <input> tag
//
//     after the first name/value pair is constructed, put "&" between
//     each value as required in "POST" data format
//
//     specifically pass the value of "data_source" which is an input type=hidden value
//     on the form which indicates if the product data comdes from etilize (SPRLIVE)
//     or our own database (LOCAL)
//
	/*
	if (request.indexOf("&") >= 0) {
		request = request.replace("&", "#|#");
	}

    postData = "request=" + request;
    postData += "&data_source=" + $("data_source").value;

	if (func == "del") {
		if (type.indexOf('|') >=0)
		del_type = type.substring(type.indexOf('|')+1, type.length);
		else
		del_type = type;
	postData += "&method=search&search_type="+searchType+"&add_type="+del_type+"&action=" + func;
	}
	else if ((searchType == "new" || searchType == "cat") && type == "result_per_page") {
		postData += "&method=search&search_type="+searchType+"&add_type="+$("add_search").value+"&pageSize="+pageSize;
	}
	else if ((searchType == "new" || searchType == "cat") && type == "sort_by") {
		if ($("category_text").style.display == "none" || $("category_text").style.display == "") {
			if (searchType == "new")
				postData += "&method=search&search_type=add&add_type=cat&sort_by="+sortBy;
			else if (searchType == "cat")
				postData += "&method=search&search_type=cat&add_type=cat&sort_by="+sortBy;
		}
		else if ($("manufacturer_text").style.display == "none" || $("manufacturer_text").style.display == "") {
			if (searchType == "new")
				postData += "&method=search&search_type=add&add_type=man&sort_by="+sortBy;
			else if (searchType == "cat")
				postData += "&method=search&search_type=cat&add_type=man&sort_by="+sortBy;
		}
		else if (($("category_text").style.display == "none" && $("manufacturer_text").style.display == "none") || ($("category_text").style.display == "" && $("manufacturer_text").style.display == "")) {
			postData += "&method=search&search_type=add&add_type=&sort_by="+sortBy;
		}
	}
	else if (typeof(func) == 'string' && (func == "nextpage" || func == "prevpage" || func.substring(0,4) == "move")) {
		postData += "&method=search&search_type="+searchType+"&add_type="+$("add_search").value+"&pageSize="+pageSize;
	}	
	else {
		postData += "&method=search&search_type="+searchType+"&add_type="+$("add_search").value;
	}
	*/
//
//   will no longer be using page number for paging,
//   but simply "nextpage" or "prevpage" as controlled by an
//   onclick= which only exists is called php determines it is valid to appear
//
    /*
    if (func) {
        if (func == "nextpage" || func == "prevpage" || func.substring(0,4) == "move") {
            postData += "&action=" + func;
        }
    }
	*/
	
//
//  now issue call to php function
//
	/*
    $("output_div").innerHTML = "";
    getPHP("/aos/modules/search/get_prod.php",postData,"output_div");
	
	buttonDo($('search_count'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=search_count', '', 'search_count', 'true', 'Please Wait', 'o');
	$("search_count").style.display = '';

	returnAjaxResult('/aos/cart/php/route_request.php?request=category_state', postData, "false", "category");
	returnAjaxResult('/aos/cart/php/route_request.php?request=manufacturer_state', postData, "false", "manufacturer");
	
	if ($("add_search").value == "new") {
		buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
		buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');
	}
	else if($("add_search").value == "cat" && searchType == "add") {
		buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');
	}
	else if($("add_search").value == "man" && searchType == "add") {
		buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
	}
	else if(filterType == "man" && searchType == "new") {
		buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');
		buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
	}
	else if(filterType == "cat" && searchType == "new") {
		buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
		buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');
	}
	else if ((searchType == "new" || searchType == "cat") && (type == "result_per_page" || type == "sort_by") && $("searchfilter").style.display == "") {
		buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
		buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');
	}
	else {
		buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
		buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');
	}
	
//
//  now that all processing is done, reinitialize request value on screen
//  so when adding to search it is not still sitting there
//
//  also set search type back to "New Search as default button checked
//
//
	*/
	if ($("requestIn")) {
		$("requestIn").value = "";
	}

    updateFilter();
//
//   always format back button so if you leave the
//   product list for ANY reason
//   you can get back
//
    formatBackButton();
}
//
//        can be called with func as follows"
//        prev = perform previous saved search (back to search results)
//        del =  delete specified search criteria and re-do search
//        if func = del then  var "filter" is the search argument to delete
//
function menuGetProductList(thisLink) {
//	alert("this object tag name = " + this.tagName);
//
//     alert("# args = " + arguments.length);
//     alert("e = " + e + " func= " + func + " filter = " + filter);
//  
//   initialize output area and collect up all <input> tags
//   also initialize "Back to Search Results" so it doesn't appear
//   as it only appears on single product display that came from selecting
//   an item on a product list
//
//   check radio button to see whether this is a new search or and "add to search"
//
	displayOff('1');
	
	if ($("backButton")) {
		$("backButton").innerHTML = "";
	}
    var request = " ";
    var el = thisLink;
    while(el !== document && el.tagName.toUpperCase() !== 'FORM') {
          el = el.parentNode;
    }
    thisLinkForm = el;
    
	
    request = thisLinkForm.elements['request'].value;
//
//   now set cookie for this search
//
	setCookie('request',request,'1');
	setCookie('search_type','cat','1');
	
	request = escape(request);
//
//
//
    var postData = "";
//
//     generalized routine loops through all input fields
//     getting the name and value and creates a string
//     for the "POST" request to send to PHP function
//
//     only do this if the <input> tag has a name attribute
//     this is checked to avoid sending things like the "submit" button
//     which is also an <input> tag
//
//     after the first name/value pair is constructed, put "&" between
//     each value as required in "POST" data format
//
//     specifically pass the value of "data_source" which is an input type=hidden value
//     on the form which indicates if the product data comdes from etilize (SPRLIVE)
//     or our own database (LOCAL)
//
    postData = thisLinkForm.elements['request'].name + "=" + request;
    postData += "&data_source=" + thisLinkForm.elements['data_source'].value;
	if (thisLinkForm.elements['data_source'].value == "SPRLIVE") {
		postData += "&method=search";
	} else {
		postData += "&method=search&search_type=cat";
	}
//
//  now issue call to php function
//
    $("output_div").innerHTML = "";
    getPHP("/aos/modules/search/get_prod.php",postData,"output_div");
	
	buttonDo($('search_count'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=search_count', '', 'search_count', 'true', 'Please Wait', 'o');
	$("search_count").style.display = '';

	buttonDo($('category'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=category', '', 'category', 'true', 'Please Wait', 'o');
	buttonDo($('manufacturer'), '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=manufacturer', '', 'manufacturer', 'true', 'Please Wait', 'o');

	returnAjaxResult('/aos/cart/php/route_request.php?request=category_state', postData, "false", "category");
	returnAjaxResult('/aos/cart/php/route_request.php?request=manufacturer_state', postData, "false", "manufacturer");

    updateFilter();
//
//   always format back button so if you leave the
//   product list for ANY reason
//   you can get back
//
    formatBackButton();
}



function setCookie(c_name,value,expiredays) {

        var exdate=new Date(); 
        exdate.setDate(exdate.getDate()+expiredays); 
        document.cookie=c_name+ "=" +escape(value)+ 
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());

} 
function getCookie(c_name) {

        if (document.cookie.length>0) {
           var c_start=document.cookie.indexOf(c_name + "="); 
           if  (c_start!=-1) {
                c_start=c_start + c_name.length+1; 
                var c_end=document.cookie.indexOf(";",c_start); 
                if (c_end==-1) {  
                    c_end=document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start,c_end)); 
           } 
        } 
        return "";

}
//
//    this function refreshes the "Currently Filtered By:"
//    portion of the screen and is called whenever a change
//    swas made tlo the search (New Search, Add to Search, or Delete)
//    based on whatever is stored in the cookie
//
function updateFilter() {
    var nextPart = new Array();
	if ($("filter")) {
		$("filter").innerHTML = "Currently Filtered By";
        $("filterContent").innerHTML ="";
		var fullRequest = getCookie("request");
		fullRequest = unescape(fullRequest);
		mergePart = fullRequest.split("+");
		fullRequest = fullRequest.replace(/[+]+/g,' ');
		nextPart = fullRequest.split("|");
		
		var typeRequest = getCookie("addtype");
		typePart = typeRequest.split("|");
				
		for (var i=0;i<nextPart.length;i++) {
		
				if(nextPart[i] != "") {
				
					if (i == 0) {
						$("filterContent").innerHTML += '<a id="' +  nextPart[i] + '" class="fontSizeCategoryNew" href="#">' + nextPart[i] + '</a><BR>';
					}
					else {
						$("filterContent").innerHTML += '<a id="' +  nextPart[i] + '" class="fontSizeCategoryNew" href="#"  onclick="getProductList(this,\'del_'+ typePart[i] + '\',\'' + escape(nextPart[i]) + '\');"><span class="del">[X]</span>' + nextPart[i] + '</a><BR>';
					}					
					$("filterContent").style.display='';
				}
		}

		$("filter").style.display='';
	}
}
//
//     this function issue XML HTTP Request using post method
//
function getPHP(phpName,postData,outId) {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }//
//     set up event handler for when asynchronous request completes
//     successfully to output results to screen element with ID of
//     "output"
//

    xmlhttp.onreadystatechange=function() {
	       //alert("Ready state = " + xmlhttp.readyState + " Status = " + xmlhttp.status);
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			if($(outId)) {
				$(outId).innerHTML = xmlhttp.responseText;
			}

			//on remove items from cart,subtotal need to be updated 
			if(phpName=='/aos/cart/php/route_request.php?request=cart_remove_item'){
				var val=xmlhttp.responseText;
				$('top_subtotal').innerHTML='Subtotal: $'+val;
				$('bottom_subtotal').innerHTML='Subtotal: $'+val;
            }
			
			//submit cart detail page
			//submiting when comments and purchase order setup in session
			if(phpName=='/aos/cart/php/route_request.php?request=checkout_data'){
				document.forms["move_to_get_payment"].submit();
			}
			//display msg when items are added to cart
			if(phpName=='/aos/cart/php/route_request.php?request=cart_add_item'){
				message=xmlhttp.responseText;
				//message = "Art&iacute;culo(s) a&ntilde;adido al carrito";
				displayMsg(message);
			}
		
			if (globalFunc != "") {
                eval(globalFunc + "()");
            }
        }
    }
     
//
//      set up to send data to PHP fucntion using "POST" method
//
    xmlhttp.open("POST",phpName,"true");
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(postData);
}
//
//    function to handle screen actions of adding to the cart - activated
//    when button is clicked
//
//    it goes through all input, if item was checked
//    adds the item's sku and quantity to a table
//    to be jused for formatting a request to the php
//    shop cart module that maintains the shopping cart
//
//    it then resets the line on the screen so it is unchecked,
//    unhighlighted and quantity is blanked out
//
function addToCart(singleSKU) {
     var skuNumber = "";
     var skuQty = 0;
     var skuSub = "sku";
     var qtySub = "qty";
     var itemSelected = false;
     var message = "";
     var cartItems = new Array();
//
//   check to see if event was selecting the main product on the
//   full product display. If so, the single sku is passed to it by
//   invoking "onclick";
//
    if (singleSKU) {
        itemSelected = true;
        cartItems[0] = new Array();
        cartItems[0][skuSub] = singleSKU;
		
		if ($('q_pop_'+singleSKU))
			cartItems[0][qtySub] = $('q_pop_'+singleSKU).value;
		else
			cartItems[0][qtySub] = 1;
    }
//
//    otherwise, go through all product list items looking for
//    those that are checked
//
    else {
            var allInput = new Array();
            allInput = document.getElementsByTagName("input");
			j = 0; 
			
           for (var i=0; i<allInput.length; i++) { 
               var type = allInput[i].type;
               if (type == "checkbox" && allInput[i].checked == 1){
                   itemSelected = true;         
				   if(allInput[i].id == "master_select" ) 
				    { continue; }
                   skuNumber = allInput[i].id.substring(1);
                   if(skuNumber){
				   skuQty = $("q" + skuNumber).value;
                   cartItems[j] = new Array();
                   cartItems[j][skuSub] = skuNumber;
                   cartItems[j][qtySub] = skuQty;
                   j++;
                   allInput[i].checked = 0;
				   $(skuNumber).style.background="";
                   $(skuNumber).className = $(skuNumber).className.replace(" highlight","");
                   $("q" + skuNumber).value = "";
                   }
               }
           }
    }
	
	
	if($('master_select'))
	$('master_select').checked = 0;

//
//    now that all data is assembled to add items to cart,
//    invoke php module to update cart/summary totals
//
//    check to see if any items were selected. If not, do not launch
//    php but return a message
    if (!itemSelected) {
        message = "No items selected";
		displayMsg(message);
    }
    else {
        //message = "Item(s) added to cart";
        getCart("add",cartItems);
    }
}

//Remove items from cart list

function cart_remove_items(list) {		
	var skuNumber = "";
	var skuQty = 0;
	var skuSub = "sku";
	var valSub = "val";
	var itemSelected = false;
	var message = "";
	var cartItems = new Array();
	var allInput = new Array();

	allInput = document.getElementsByTagName("input");
	j = 0; 
	
	//hide and delete all sku's when select all checked
	if($('master_select')){
		if($('master_select').checked == 1){
			$('shopping_cart').style.display='none';
			$('msg').innerHTML='<div class="view_cart_no_item">There are no items in your cart.</div>';
			getCartPHP("rem_all_cart",'');
			return;
		}
	}
			
	for (var i=0; i < allInput.length; i++) {
		var type = allInput[i].type;

		if (type == "checkbox" && allInput[i].checked == 1) {
			skuNumber = allInput[i].id.substring(1);

			//avoiding master select box in select all case.
			avoid_sku = allInput[i].id.substring(0);

			if(avoid_sku!='master_select' && $("s" + skuNumber)){
				itemSelected = true;
				skuval = $("s" + skuNumber).value;
				cartItems[j] = new Array();
				cartItems[j][skuSub] = skuNumber;
				cartItems[j][valSub] = skuval;
				j++;
			}
		}
	}

	//hide all <tr> of sku's those where deleted
	k=0;

	for (var i=0; i < cartItems.length; i++) {
		$('s'+cartItems[k][skuSub]).removeAttribute('id');
		$(cartItems[k][skuSub]).style.display='none';
		$('sku_count').innerHTML='0';
		k++;
	}
	
	//set cart status when items deleted   
	count=0; 
	
	for (var i=0; i < allInput.length; i++) {
		var type = allInput[i].type;
		
		if (type == "checkbox"){
			count++;
		}
	}
	
	if(count==2){
		$('shopping_cart').style.display='none';
		$('msg').innerHTML='<div class="view_cart_no_item">There are no items in your cart.</div>';
	}	
		   
	if (itemSelected==false) {
		message = "No items selected for removal";
    }
    else{
		message = "Item(s) remove from cart";
		getCart("rem_cart",cartItems);
    }

	displayMsg(message);
}

// remove items from favorite

function fav_remove_items(list)
{			
			var skuNumber = "";
			var skuQty = 0;
			var skuSub = "sku";
			var valSub = "val";
			var itemSelected = false;
			var message = "";
			var cartItems = new Array();
			
			
			var allInput = new Array();
            allInput = document.getElementsByTagName("input");
			j = 0; 
			
			//hide and delete all sku's when select all checked
			if($('master_select')){
			if($('master_select').checked == 1){
			$('toptable_fav').style.display='none';
			$('topDivOnFavorite').innerHTML='Actualmente no tienes ningun articulo en favoritos.';
			getCartPHP("rem_all_fav",'');
			return;
			}
			}
			
           for (var i=0; i < allInput.length; i++) { 
               var type = allInput[i].type;
               if (type == "checkbox" && allInput[i].checked == 1){
                   skuNumber = allInput[i].id.substring(1);
				   //avoiding master select box in select all case.
				   avoid_sku = allInput[i].id.substring(0);
				   if(avoid_sku!='master_select' && $("s" + skuNumber)){
				    itemSelected = true;
					skuval = $("s" + skuNumber).value;
					cartItems[j] = new Array();
					cartItems[j][skuSub] = skuNumber;
					cartItems[j][valSub] = skuval;
					j++;
					}
			   }
           }
		   
		   //hide all <tr> of sku's those where deleted
		   k=0;
		  for (var i=0; i < cartItems.length; i++) { 
					$('s'+cartItems[k][skuSub]).removeAttribute('id');
					$(cartItems[k][skuSub]).style.display='none';
					$('sku_count').innerHTML='0';
					k++;
			}
		   
		//set status when items deleted   
		count=0; 
		for (var i=0; i < allInput.length; i++) { 
               var type = allInput[i].type;
               if (type == "checkbox" && allInput[i].checked == 0){
				count++;
			   }
			}
			$('fav_count').innerHTML=count-1;
			if(count==1){
			$('toptable_fav').style.display='none';
			$('topDivOnFavorite').innerHTML='Actualmente no tienes ningun articulo en favoritos..';
			}	
		   
	 if (itemSelected==false) {
        message = "No items selected for removal";
		}
	else {
        message = "Item(s) remove from favorite";
        getCart("rem_fav",cartItems);
    }
    displayMsg(message);

}



//
//    function to handle screen actions of adding to the favorites
//
//    it goes through all input, if item was checked
//    adds the item's sku and quantity to a table
//    to be jused for formatting a request to the php
//    favorite module that maintains the favorite list
//
//    it then resets the line on the screen so it is unchecked,
//    unhighlighted and quantity is blanked out
//
function addToFav(singleSKU) {

     var skuNumber = "";
     var skuQty = 0;
     var skuSub = "sku";
     var qtySub = "qty";
     var itemSelected = false;
     var message = "";
     var cartItems = new Array();
//
//   check to see if event was selecting the main product on the
//   full product display. If so, the single sku is passed to it by
//   invoking "onclick";
//
    if (singleSKU) {
        itemSelected = true;
        cartItems[0] = new Array();
        cartItems[0][skuSub] = singleSKU;
        cartItems[0][qtySub] = 1;
    }
//
//    otherwise, go through all product list items looking for
//    those that are checked
//
    else {
            var allInput = new Array();
            allInput = document.getElementsByTagName("input");
			j = 0; 
			
           for (var i=0; i<allInput.length; i++) { 
               var type = allInput[i].type;
               if (type == "checkbox" && allInput[i].checked == 1){
                   skuNumber = allInput[i].id.substring(1);
                   avoid_sku = allInput[i].id.substring(0);
				   if(avoid_sku!='master_select'){
				   if(skuNumber){
				   itemSelected = true;
				   skuQty = $("q" + skuNumber).value;
                   cartItems[j] = new Array();
                   cartItems[j][skuSub] = skuNumber;
                   cartItems[j][qtySub] = skuQty;
                   j++;
                   allInput[i].checked = 0;
				   $(skuNumber).className="";
                   //$("q" + skuNumber).value = "";
				   }
				   }
               }
           }
    }
	
	//If select all checked than uncheck 
	if($('master_select'))
	$('master_select').checked = 0;
	
//
//    now that all data is assembled to add items to cart,
//    invoke php module to update cart/summary totals
//
//    check to see if any items were selected. If not, do not launch
//    php but return a message
    if (!itemSelected) {
        message = "No items selected for favorite";
    }
    else {
        message = "Art&iacute;culo(s) a&ntilde;adido al favoritos";
        getCart("fav",cartItems);
    }
    displayMsg(message);
}


//
//
//    function to handle screen actions of adding to the cart from customer quick order entry screen
//    which has multiple lines so all have to be gotten
//
//    activated when "Add to cart" button is clicked
//
//    it goes through all input within this form, if item was entered
//    adds the item's sku and quantity to a table
//    to be used for formatting a request to the php
//    shop cart module that maintains the shopping cart
//
//    it then resets the line on the screen so 
//    quantity is blanked out
//
function quickAddToCart(thisButton) {
//    alert("entering quickAddToCart");
//    alert("this = " + thisButton);
//    alert("this field id = " + thisButton.id);
//    alert("this form name = " + thisButton.form.name);
     
	 var skuNumber = "";
     var skuQty = 0;
     var skuSub = "sku";
     var qtySub = "qty";
     var itemSelected = false;
     var errorsFound = false;
     var message = "";
     var cartItems = new Array();
//
//    go through all quick entry sku and qty fields looking for
//    those that are filled in
//
        var allInput = new Array();
        allInput = document.getElementsByTagName("input");
        var j = -1;
		
        for (var i=0; i<allInput.length; i++) { 
           if (allInput[i].form.name == thisButton.form.name) {
                var type = allInput[i].type;
                if (type == "text" && allInput[i].value != ""){
                    itemSelected = true;
                    if (allInput[i].id.indexOf('sku') != -1) {
                        j++;
                        cartItems[j] = new Array();
                        skuNumber = allInput[i].value;
                        cartItems[j][skuSub] = skuNumber;
                        var nextQty = allInput[i+1];
                        if (nextQty.value == "") {
                            nextQty.value = "1";
                        }
                        else {
                            if (parseInt(nextQty.value,10) < 0 || isNaN(nextQty.value)) {
								nextQty.className += " invalid";
								nextQty.value = "?";
								if (!errorsFound) { 
									errorsFound = true;
									nextQty.focus();
								}
                            }
                            else {
								nextQty.className = nextQty.className.replace(/invalid/g,"");
                            }
                        }
					    var	sku_found = i;
                    }
                    else {
						if (allInput[i].id.indexOf('qty') != -1  &&  i==(sku_found+1)) {
							skuQty = allInput[i].value;
							cartItems[j][qtySub] = skuQty;
						}
                    }
                }
           }
        }
//
//    now that all data is assembled to add items to cart,
//    invoke php module to update cart/summary totals
//
//    check to see if any items were selected. If not, do not launch
//    php but return a message
    if (!itemSelected) {
        message = '<span style="font-weight:bold;color:red;">No items entered</span>';
        displayMsg(message);

    }
    else {
        if (errorsFound) {
            message = '<span style="font-weight:bold;color:red;">Missing Quantity</span>';
            displayMsg(message);

        }
        else { 
			message = "Item(s) Adding to cart..... Please Wait !";
			displayMsg(message);
			getCart("add",cartItems);
			var postData = "message=" + message;
			
			// below code added for making input blank
			j=0;
			 for (i=0; i<allInput.length; i++)
			 {
					if (allInput[i].id.indexOf('sku') != -1) 
								{
								j++;
								var qs = "quick_sku"+j;
								var qq = "quick_qty"+j;
								document.getElementById(qs).value = '';
								document.getElementById(qq).value = '1';
								}
				}
			//globalFunc = "suggestOptions";
			//alert("globalFunc set to " + globalFunc);
			getPHP("/aos/cart/php/route_request.php?request=customer_quick_order",postData,"output_div");
			
			message = "All valid item(s) added to cart.";
			displayMsg(message);
			
			//var signal = returnAjaxResult("/aos/cart/php/route_request.php?request=customer_quick_order",null,false,"");
			//alert(signal);
			globalFunc = "";
        }
    }
    
}


//
//    function to handle screen actions of adding to the cart from dealer quick order entry screen
//    which has only one line of entry 
//    
//    activated when "Add to cart" button is clicked
//
//    if item was entered
//    adds the item's sku and quantity to a table
//    to be jused for formatting a request to the php
//    shop cart module that maintains the shopping cart
//
//    it then resets the screen by re-invoking the dealer quick order entry module 
//
function dealerQuickAddToCart(thisButton) {
//    alert("entering quickAddToCart");
//    alert("this = " + thisButton);
//    alert("this field id = " + thisButton.id);
//    alert("this form name = " + thisButton.form.name);
     var skuNumber = "";
     var skuQty = 0;
     var skuSub = "sku";
     var qtySub = "qty";
     var itemSelected = false;
     var errorsFound = false;
     var message = "";
     var cartItems = new Array();
//
//    go through all quick entry sku and qty fields looking for
//    those that are filled in
//
        var allInput = new Array();
        allInput = document.getElementsByTagName("input");
        var j = -1;
		
        for (var i=0; i<allInput.length; i++) { 
           if (allInput[i].form.name == thisButton.form.name) {
                var type = allInput[i].type;
                if (type == "text" && allInput[i].value != ""){
                    itemSelected = true;
                    if (allInput[i].id.indexOf('sku') != -1) {
                        j++;
                        cartItems[j] = new Array();
                        skuNumber = allInput[i].value;
                        cartItems[j][skuSub] = skuNumber;
                        var nextQty = allInput[i+1];
                        if (nextQty.value == "") {
                            nextQty.value = "1";
                        }
                        else {
                            if (parseInt(nextQty.value,10) < 0 || isNaN(nextQty.value)) {
								nextQty.className += " invalid";
								nextQty.value = "?";
								if (!errorsFound) { 
									errorsFound = true;
									nextQty.focus();
								}
                            }
                            else {
                                nextQty.className = nextQty.className.replace(/invalid/g,"");
                            }
                        }
                    }
                    else {
						if (allInput[i].id.indexOf('qty') != -1) {
							skuQty = allInput[i].value;
							cartItems[j][qtySub] = skuQty;
						}
                    }
                }
            }
        }
//
//    now that all data is assembled to add items to cart,
//    invoke php module to update cart/summary totals
//
//    check to see if any items were selected. If not, do not launch
//    php but return a message
    if (!itemSelected) {
        message = '<span style="font-weight:bold;color:red;">No items selected</span>';
        displayMsg(message);

    }
    else {
        if (errorsFound) {
            message = '<span style="font-weight:bold;color:red;">Missing Quantity</span>';
            displayMsg(message);

        }
        else { 
//            displayMsg(message);

            getCart("add",cartItems);
//            globalFunc = "suggestOptions";
//            alert("globalFunc set to " + globalFunc);
            buttonDo(thisButton,'','ajax','n','/aos/modules/quick_order/dealer_quick_order.php','','output_div','false','','',suggestOptions);
            globalFunc = "";

        }
    }
}

//
//    this function simply displays an error message in the
//    element specified by the "id" passed to it
function displayMsg(message) {
    var message;
    $("errormsg").innerHTML = message;
}
//
//    if an element on the product list is selected
//    highlight it by changing its class
//
function showSelected(id) {
    if ($("s" + id).checked == 1) {
        $(id).className = " highlight";
		if($("q" + id).value=='' || $("q" + id).value == 0){
        $("q" + id).value = 1;
		$(id).value = 1;
		}
    }
    else {
        $(id).className = '';
		
		if ($('master_select')) {
			$('master_select').checked=0;
		}
	}
	
	
}
//check or uncheck all
function checkedAll () {

	var allInput = $$("input","select","textarea");
	var j=0;
	var id_array=new Array();
	for (var i=0;i<allInput.length;i++) {
		if(allInput[i].type == "checkbox") {
			if(allInput[i].id != "") {
				var str=allInput[i].id;
				var newStr = str.substring(1);
				id_array[j]=newStr;
				j++;
			}
		}	
	}
		
	if($('master_select').checked == true)
		checked = true;
	else
		checked = false;
	
	if(checked == true){
		for(var i=1;i<id_array.length;i++){
			$(id_array[i]).className = " highlight";
			$('s'+id_array[i]).checked = true;
				if($('q'+id_array[i]).value=='')
				$('q'+id_array[i]).value=1;
		}
	}
	$('sku_count').innerHTML=i-1;
	
	/*
	//count selected
	var count=0;
	for(var i=1;i<id_array.length;i++){
		if($('s'+id_array[i]).checked ==true)
		count++;
	}
	*/
	
	
	
	if (checked == false){
		for(var i=1;i<id_array.length;i++){
			$(id_array[i]).className = " ";
			$('s'+id_array[i]).checked = false;
			$('sku_count').innerHTML='0';
		}
	}

	
}

function count_selected_updated()
{
var allInput = $$("input","select","textarea");
	var j=0;
	var id_array=new Array();
	
	for (var i=0; i < allInput.length; i++) {
		if (allInput[i].type == "checkbox" && allInput[i].checked ==1) {
			if(allInput[i].id != "") {
				if (allInput[i].id != "master_select") {
					j++;
				}
			}
		}	
	}
        var msg_display="";
        if(j>0)
            msg_display = "You have currently selected "+j+" items.";
	if($('sku_count'))
	$('sku_count').innerHTML=msg_display;	

}
//count for sku selected
function count_selected()
{
var allInput = $$("input","select","textarea");
	var j=0;
	var id_array=new Array();
	
	for (var i=0; i < allInput.length; i++) {
		if (allInput[i].type == "checkbox" && allInput[i].checked ==1) {
			if(allInput[i].id != "") {
				if (allInput[i].id != "master_select") {
					j++;
				}
			}
		}	
	}
	
	if($('sku_count'))
	$('sku_count').innerHTML=j;	

}

function toggle_visibility(id) {
   var e = document.getElementById(id);
   
   if(e.style.display == 'block') {
	  e.style.display = 'none';
   }
   else {
	  e.style.display = 'block';
   }
}

function toggel_doller_percent(id){
if(id=='doller'){
$('doller').innerHTML='';
$('doller').innerHTML='$';
}
if(id=='percent'){
$('doller').innerHTML='';
$('doller').innerHTML='%';
}
}

function imgAppear(thisObj,imgId) {
    if(navigator.appName !== "Microsoft Internet Explorer") { 
        new Effect.Appear(imgId, {duration: 0.5});
    }
    else { 
        $(imgId).style.display = 'block';
    }
    return false;    
}

function imgFade(thisObj,imgId) {
    if(navigator.appName !== "Microsoft Internet Explorer") { 
        new Effect.Fade(imgId, {duration: 0.5});
    }
    else {
        $(imgId).style.display = 'none';
    }
    return false;    
}
function isImageOk(img) {
// However, they do have two very useful properties:
// naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
/*
    if (typeof img.width != "undefined"
            &&
               img.width == 0) {
        return false;
    }
*/                                                                               
// No other way of checking: assume it's ok.
    return true;
}

function checkImg(thisImg) {
    if (navigator.appName != "Microsoft Internet Explorer") {
        if (thisImg.naturalWidth == 0) {
            thisImg.src = 'aos/cart/images/no_image_avail.gif';
        }
    }
}

function fixImg(thisImg) {
    thisImg.src = '../../../aos/cart/images/no_image_avail.gif';
}

function newfixImg(thisImg,thisSrcImage) {
	thisImg.src = thisSrcImage;
}

//remove promo code from current cart
function remove_promo(promo_value){
	getPHP("/aos/cart/php/route_request.php?request=cart_remove_promo");
	
	$('discount_promo').style.display='none';
	$('errormsg').innerHTML ='Promo Code deleted';
	
	grand_total=$('grand_total').value;
	grand_total=parseFloat(grand_total)+parseFloat(promo_value);
	grand_total=grand_total.toFixed(2);
	
	$('grand_total_format').innerHTML ='$'+grand_total;
	$('grand_total').value = grand_total;
	
	postData = '&data=' + grand_total;
	
	getPHP("/aos/cart/php/route_request.php?request=grand_total_update",postData);
	
	//$('updated_total').innerHTML ='del'+grand_total;
}

function remove_reward(reward_value){
	
	getPHP("/aos/cart/php/route_request.php?request=remove_reward");
	$('discount_reward').style.display='none';
	grand_total=$('grand_total').value;
	grand_total=parseFloat(grand_total)+parseFloat(reward_value);
	
	grand_total=grand_total.toFixed(2);
	
	$('grand_total_format').innerHTML ='$'+grand_total;
	$('grand_total').value = grand_total;
	
	postData = '&data=' + grand_total;
	
	getPHP("/aos/cart/php/route_request.php?request=grand_total_update",postData);
}

function fillPublicationInRule(phpName,postData,outId) {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }//
//     set up event handler for when asynchronous request completes
//     successfully to output results to screen element with ID of
//     "output"
//

    xmlhttp.onreadystatechange=function() {
//        alert("Ready state = " + xmlhttp.readyState + " Status = " + xmlhttp.status);
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            while ($(outId).length > 0) {
                $(outId).removeChild($(outId)[0]);
            }
            $(outId).innerHTML = xmlhttp.responseText;
//            alert("globalFunc = " + globalFunc);
            if (globalFunc != "") {
                eval(globalFunc + "()");
            }
//            alert("response received " + xmlhttp.responseText);
        }
    }

//
//      set up to send data to PHP fucntion using "POST" method
//
    xmlhttp.open("POST",phpName,"true");
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(postData);

}
//
//first check user credentials for any error msg if every thing is ok
//login form submitted and redirected to previous page
//
function user_login_chk() {
var user=$('user').value;
var pass=$('pass').value;
var postData = "&user="+$('user').value+"&pass="+$('pass').value+"&action=login";
var data=returSynAjaxResult('/aos/cart/php/route_request.php?request=chk_user_credentials', postData, "true");
if(data=='done'){
var url= returSynAjaxResult('/aos/cart/php/route_request.php?request=login', postData, "true");
window.location=url;
}
else{
//$('login_error').innerHTML='login credentials failed';
BetterInnerHTML(document.getElementById("login_error"), "Login Failed"); 
}
}


function returnAjaxResult(phpName,postData, sync_type, outId) {
    var xmlhttp;
	var result;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }//
//     set up event handler for when asynchronous request completes
//     successfully to output results to screen element with ID of
//     "output"
//

    xmlhttp.onreadystatechange=function() {
//        alert("Ready state = " + xmlhttp.readyState + " Status = " + xmlhttp.status);
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            result = xmlhttp.responseText;

			if (outId == "category") {
				if (result == "true") {
					$("category_text").style.display = '';
					$("category_select").style.display = '';
				}
				else {
					$("category_text").style.display = 'none';
					$("category_select").style.display = 'none';
				}
			}
			
			if (outId == "manufacturer") {
				if (result == "true") {
					$("manufacturer_text").style.display = '';
					$("manufacturer_select").style.display = '';
				}
				else {
					$("manufacturer_text").style.display = 'none';
					$("manufacturer_select").style.display = 'none';
				}
			}

			if ($("category_select").style.display == '' || $("manufacturer_select").style.display == '') {
				$("searchfilter").style.display='';	
			}
			else {
				$("searchfilter").style.display='none';	
			}			
        }
		else {
			result = "false";
		}
    }

//
//      set up to send data to PHP fucntion using "POST" method
//
    xmlhttp.open("POST",phpName, sync_type);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(postData);

	return result;
}

//Synchronous Ajax response
function returSynAjaxResult(phpName,postData, sync_type){
    var xmlhttp;
	var result;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }//
	
    xmlhttp.open("POST",phpName,false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(postData);
	return xmlhttp.responseText;
}

function companyNameUpdate(obj)
{
if(obj.checked)
{
document.getElementById('company_name').disabled=true;
document.getElementById('company_name').value="";
}
else
{
document.getElementById('company_name').disabled=false;
}
}

function companyUpdate(obj)
{
if(obj.checked)
{
document.getElementById('company_name').disabled=true;
document.getElementById('company_name').value="";
document.getElementById('input2').disabled=true;
}
else
{
document.getElementById('company_name').disabled=false;
document.getElementById('input2').disabled=false;
}
}


function setDate(exp_date){
	if(document.getElementById('input3')!=null){

		if(("<?php echo date('d/m/y'); ?>").indexOf(document.getElementById('input3').value)!=-1 ){
			document.getElementById('input3').value=exp_date;
		}
	} 
}

function disableShippingAddress(form_name) {
	if (form_name.cadmin_ship_add_same.checked) {
		//form_name.cadmin_ship_location.disabled = 'true';
		form_name.cadmin_ship_add1.disabled = 'true';
		form_name.cadmin_ship_add2.disabled = 'true';	
		form_name.cadmin_ship_add3.disabled = 'true';
		form_name.cadmin_ship_city.disabled = 'true';
		form_name.cadmin_ship_state.disabled = 'true';	
		form_name.cadmin_ship_zip.disabled = 'true';
		//Assigning same value as billing address
		form_name.cadmin_ship_add1.value=form_name.cadmin_bill_add1.value;
		form_name.cadmin_ship_add2.value=form_name.cadmin_bill_add2.value;
		form_name.cadmin_ship_add3.value=form_name.cadmin_bill_add3.value;
		form_name.cadmin_ship_city.value=form_name.cadmin_bill_city.value;
		form_name.cadmin_ship_state.value=form_name.cadmin_bill_state.value;
		form_name.cadmin_ship_zip.value=form_name.cadmin_bill_zip.value;
		
		
	}
	else {
		//form_name.cadmin_ship_location.disabled = '';
		form_name.cadmin_ship_add1.disabled = '';
		form_name.cadmin_ship_add2.disabled = '';	
		form_name.cadmin_ship_add3.disabled = '';
		form_name.cadmin_ship_city.disabled = '';
		form_name.cadmin_ship_state.disabled = '';	
		form_name.cadmin_ship_zip.disabled = '';
		}
}
function disableShippingAddressDC(form_name) {
	if (form_name.add_check.checked) {
		//form_name.add_location.disabled = 'true';
		form_name.add_line_1.disabled = 'true';
		form_name.add_line_2.disabled = 'true';	
		form_name.add_line_3.disabled = 'true';
		form_name.add_city.disabled = 'true';
		form_name.add_state.disabled = 'true';	
		form_name.add_zip.disabled = 'true';
		
	}
	else {
		//form_name.add_location.disabled = '';
		form_name.add_line_1.disabled = '';
		form_name.add_line_2.disabled = '';	
		form_name.add_line_3.disabled = '';
		form_name.add_city.disabled = '';
		form_name.add_state.disabled = '';	
		form_name.add_zip.disabled = '';
		
	}
}

function disablePasswordReset(form_name) {
	if (form_name.cadmin_ship_password_same.checked) {
		form_name.acct_password.disabled = 'true';
		form_name.acct_password_retype.disabled = 'true';
		}
	else {
		form_name.acct_password.disabled = '';
		form_name.acct_password_retype.disabled = '';
	}
}
function disablePaymentChange(form_name,checkBoxObj)
{

if(checkBoxObj.checked)
{
form_name.account_name.disabled=true;
form_name.payment_type.disabled=true;
form_name.acc_holder_name.disabled=true;
form_name.acc_holder_address.disabled=true;
form_name.acc_holder_zip.disabled=true;
form_name.expire_month.disabled=true;
form_name.expire_year.disabled=true;
form_name.security_code.disabled=true;
}
else
{
form_name.account_name.disabled=false;
form_name.payment_type.disabled=false;
form_name.acc_holder_name.disabled=false;
form_name.acc_holder_address.disabled=false;
form_name.acc_holder_zip.disabled=false;
form_name.expire_month.disabled=false;
form_name.expire_year.disabled=false;
form_name.security_code.disabled=false;
}
}

function changePayType(thisTag){
	ptype = $(thisTag.id).selectedIndex;
	pname = String( $(thisTag.id).options[ptype].getAttribute('type'));
	
	if (pname == 'CC'){
		for (i=27; i<=33; i++) {
			$('input'+i).disabled = '';
			$('input'+i).value = '';
		}

		//$('linput27').innerHTML = '<span class="heading-star">* </span>Credit Card Number:';
	/*} else if(pname == 'TERMS'){
		for (i=27; i<=28; i++) {
			$('input'+i).disabled = '';
			$('input'+i).value = '';
		}
		
		for (i=29; i<=33; i++) {
			$('input'+i).disabled = true;
			$('input'+i).value = 'N/A';
		}
	*/
		//$('linput27').innerHTML = '<span class="heading-star">* </span>Account Number or Business Name:';
	} else if (pname=='PHONE' || pname == 'TERMS'){

		for (i=27; i<=33; i++) {
			$('input'+i).disabled = true;
			$('input'+i).value = 'N/A';
		}
	}
}

function changePayType_info(thisTag) {
	ptype = $(thisTag.id).selectedIndex;
	pname = String( $(thisTag.id).options[ptype].getAttribute('type'));

	if (pname == 'CC') {
		for (i=2; i<=8; i++) {
			$('input'+i).disabled = '';
			$('input'+i).style.display = '';
			$('input'+i).value = '';
			$('linput'+i).style.display = '';
		}
	}
	else if (pname == 'PHONE' || pname == 'TERMS') {
		for (i=2; i<=8; i++) {
			$('input'+i).disabled = true;
			$('input'+i).value = 'N/A';
			$('input'+i).style.display = 'none';
			$('linput'+i).style.display = 'none';
		}
	}
}

function updatePayType(thisTag, num){
	ptype = $(thisTag.id).selectedIndex;
	pname = String( $(thisTag.id).options[ptype].getAttribute('type'));
	
	if (pname == 'CC'){
		for (i=2; i<=6; i++) {
			$('input'+i).disabled = '';
			$('input'+i).value = '';
		}

		$('linput2').innerHTML = '<span class="heading-star">* </span> Credit Card Number:';
	} else if(pname == 'TERMS'){
		for (i=2; i<=3; i++) {
			$('input'+i).disabled = '';
			$('input'+i).value = '';
		}
		
		for (i=4; i<=6; i++) {
			$('input'+i).disabled = true;
			$('input'+i).value = 'N/A';
		}

		$('linput2').innerHTML = '<span class="heading-star">* </span>Account Number or Business Name:';
	}
}

function select_all(count, order_obj, result) {
	if (result.checked) {
		for(var i=1; i <= count; i++) {
			$(order_obj + "" + i).checked = true;
		}
	}
	else {
		for(var i=1; i <= count; i++) {
			$(order_obj + "" + i).checked = '';
		}
	}
}

function validate_capture(count) {
	for(var i=1; i <= count; i++) {
		if ($("order_number" + i).checked == true) {
			if ($("amount_org" + i).value >= $("amount_paid" + i).value) {
				buttonDo($('order_lkup'), '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=order_capture', '', 'output_div', 'true', 'Please Wait', 'o');
			}
			else {
				alert("Amount paid can't be greater than amount charged!");
			}
		}
	}
}

function shipping_backorder(obj, obj1, obj2, type, count) {
	if (type == "q") {
		$("total_price_"+count).innerHTML = "<b>Ext: $ " + new Number($(obj.id).value*$("price_"+count).value).toFixed(2) + "</b>";
		if ($(obj.id).value > $(obj1).value) {
			$(obj2).value = parseInt($(obj.id).value) - parseInt($(obj1).value);
			$("td_"+obj2).innerHTML = parseInt($(obj.id).value) - parseInt($(obj1).value);
		}
		else if ($(obj.id).value <= $(obj1).value) {
		$(obj1).value = $(obj.id).value;
		$(obj2).value = 0;
		$("td_"+obj2).innerHTML = 0;
		}
	}
	else if (type == "s") {
		if (parseInt($(obj1.id).value) >= parseInt($(obj).value)) {
			$(obj1.id).value = parseInt($(obj).value);
			$(obj2).value = 0;
			$("td_"+obj2).innerHTML = 0;
		}
		else {
			$(obj2).value = parseInt($(obj).value) - parseInt($(obj1.id).value);
			$("td_"+obj2).innerHTML = parseInt($(obj).value) - parseInt($(obj1.id).value);
		}
	}
	else if (type == "p") {
		$("total_price_"+count).innerHTML = "<b>Ext: $ " + new Number($(obj.id).value*$(obj1.id).value).toFixed(2) + "</b>";
	}
	
}

function changeOrderQty(type,index,order,sku){	
	var shipped_qty  = type + '_'+index;
	var shipped = document.getElementById(shipped_qty).value;
	var postData = "shippedQty=" + shipped +"&orderNumber=" + order +"&item=" + sku + "&type="+type;
	getPHP("/dealer_mngt/route_request.php?request=update_shipped_quantity",postData,'output_div');
	
}

function forwardURL() {
	displayOff('1');

	if (!$("output_div")) {
		$("illst").innerHTML="";
		$("content").innerHTML='<div id="output_div"></div>';
	}
}

function displayOff(state) {
	if (state == '0') {
		$("sidebar").style.display = 'none';
		$("search_count").style.display = 'none';
		$("filter").style.display = 'none';
		$("filterContent").style.display = 'none';
		$("searchfilter").style.display = 'none';
		$("content").style.width="718px";
	}
	else if (state == '1') {
		$("sidebar").style.display = 'block';
		$("content").style.width="515px";
	}
}

function show_sku_list(itemId,divId) {
	tableObject=document.getElementById(divId);
	inputElems=document.getElementsByTagName('input');
	
	var j=0;
	var i=0;
	
    for(i=0; i < inputElems.length; i++) {
		if(inputElems[i].id.indexOf(itemId)!=-1) { 
			j++;
			suggestOptions(itemId+j);
		}
    }
	
}

function add_order(itemId,itemQty,divId) {
    tableObject=document.getElementById(divId);
	inputElems=document.getElementsByTagName('input');
	
	var j=0;
	var i=0;
	
    for(i=0; i < inputElems.length; i++) {
		if(inputElems[i].id.indexOf(itemId)!=-1) {
			j++;
		}
    }
	
	j=j+1;
	
	var newRow=tableObject.insertRow(j);
	var cell1=newRow.insertCell(0);
	var cell2=newRow.insertCell(1);
	var cell3=newRow.insertCell(2);
	var cell4=newRow.insertCell(3);
	var cell5=newRow.insertCell(4);
	
	cell1.className='right';
	cell2.className='twentyFiveWidth';
	cell4.className='right';
	cell5.className='thirtyWidth';
	
	nextitemId=itemId+j;
	nextQtyId=itemQty+j;
	
	cell1.innerHTML= j+". Sku#:";
	cell2.innerHTML="<input type='text' id='"+nextitemId+"' value='' onkeydown='enterSubmit(this,event)' />";
    cell4.innerHTML="Qty:";
	cell5.innerHTML="<input type='text' id='"+nextQtyId+"' value='1' size='4' onkeydown='enterSubmit(this,event)' />";
	suggestOptions(nextitemId);
}

function table_display(obj) {
	if(("Credit Card").indexOf(obj.value)!=-1) {
	   document.getElementById('card_use_other_card').style.display='block';
	}
	else {
	   document.getElementById('card_use_other_card').style.display='block';
	}
}


/**
 * Returns the windows width or height based on the variable passed.
* param val A string "w" or "W" for width and "h" or "H" for height.
 */
function winSize(val) {
	var result;
	if (val == "w" || val == "W") {
		if (window.innerWidth) {
		result = window.innerWidth;
		}
		else if (document.documentElement && document.documentElement.clientWidth) {
		result = document.documentElement.clientWidth;
		}    
		else if (document.body) {
		result = document.body.clientWidth;
		}
	}
	else if (val == "h" || val == "H") {
		if (window.innerHeight) {
		result = window.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight) {
		result = document.documentElement.clientHeight;
		}    
		else if (document.body) {
		result = document.body.clientHeight;
		}
	}

return result;
}
/**
Quick view hide and show function
*/
function quickViewHideShow(val, obj, obj1) {
	$(obj).style.width = winSize("w") + "px";
	$(obj).style.height = winSize("h") + "px";
	//$(obj1).style.width = winSize("w") + "px";
	//$(obj1).style.height = winSize("h") + "px";

	if (val == '1') {
		if (obj.indexOf("quickHideDiv_") != -1) {
			var newobj = obj.replace("quickHideDiv", "quickViewSkuAdd");
			$(newobj).innerHTML = "";
			$(newobj).style.display = 'none';
		}
		
		if ( document.body.filters )
			$(obj).style.filter = "alpha( opacity = " + 50 + " )";
		else
			$(obj).style.opacity = 50 / 100;
			
		$(obj).style.display='block';
	}
	else
		$(obj).style.display='none';
}

function code_data(obj, val) {
	if(val.indexOf('cd/')>=0)
	$(obj).value = encodeURIComponent(val);
}

function displayHTML(url, profile, printContent) {
	
	var inf = printContent;
	var windowWidth = "600px";
	var windowHeight = "600px";
	var windowLeft = "600px";
	var windowTop = "600px";
	var windowOptions = "width=" + windowWidth + ", height=" + windowHeight + ", left=" + windowLeft + ", top=" + windowTop + ", resizable=no, menubar=yes, status=no, scrollbars=yes";
	var win=window.open(url, profile, windowOptions);
	
	win.document.write("<html><head>");
	win.document.write("<LINK REL=StyleSheet HREF='../dealer_mngt/order_mngt_print.css' TYPE='text/css'>");
	win.document.write("</head><body><div style='width:auto;height:auto;border:1px solid black;'>");
	win.document.write(inf);
	win.document.write("</div>");
	win.document.write("<br><br><input type=button class='Button' style='align:center; margin-bottom: 5px; margin-right: 10px; cursor:hand' value='Print' onClick='window.print()'>");
	
	win.document.write("</body></html>");

		if (navigator.userAgent.indexOf('MSIE') != -1) {
		win.location.reload();
		}
	win.document.close();
}

function sort_table(val)
{
var postData = "&sort_by="+val;
getPHP("/dealer_mngt/route_request.php?request=list_po_refined",postData,'output_div');
}

function disablePassword(check)
{
 if(check==1)
 {
  document.getElementById('password_reset').disabled='disabled';
  
 }
 else
 {
 document.getElementById('password_reset').disabled='';
 }
}

function checkForValidation(obj,val) {
	if (document.getElementById('purchase_order').value=='') {
		document.getElementById('errormsg').innerHTML="Please provide Purchase Order value.";
	}
	else if (document.getElementById('department') && document.getElementById('department').value=='') {
		document.getElementById('depterrormsg').innerHTML="Please select department.";
	}
	else {
		document.getElementById('errormsg').innerHTML="";
		if (document.getElementById('depterrormsg')) {
		document.getElementById('depterrormsg').innerHTML="";}
		
		if(val == 1) {
			buttonDo(obj, '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=call_auth_net', '', 'content', 'true', '', '');
		}
		else if(val == 2) {
			buttonDo(obj, '', 'ajax', 'n', '/aos/cart/php/route_request.php?request=terms_acct', '', 'content', 'true', '', '');
		}
		else {
			get_checkout_data();
		}
	}
}

function set_department(cid){
var dept=document.getElementById('department').value;
var postData = "&cid="+cid+"&dept="+dept;
getPHP("/aos/cart/php/route_request.php?request=set_department",postData,'');
}

function createNewOrder(obj, url) {
	var new_order_number = returSynAjaxResult(url, "", "false"); 
	buttonDo(obj, '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=order_search_edit&order_no='+new_order_number, '', 'output_div', 'true', 'Please Wait', 'o'); 
	buttonDo(obj, '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=order_mngt&order_enable=1&order_no='+new_order_number, '', 'special_links', 'true', 'Please Wait', 'o');
}

//
//Dealer mng : When user check Automatically Renew Budget check box
//renew budget duration(day/month/year) will be activated or vise versa
//
function budget_renew_check(){
if($('input6').checked==true){
$('renew_budget_duration').style.display="";
$('input7').setAttribute("class", "reqd");
$('input8').setAttribute("class", "reqd");
}
else{
$('renew_budget_duration').style.display="none";
$('input7').setAttribute("class", "");
$('input8').setAttribute("class", "");
}
}
//
//add managers in department
//num var gives how many user are available for dept mang
//if users are less than 5 than no need to show up all 5 drop downs
//
function add_manager(num){
if($('manager_2').style.display =='none' && num>1){
$('manager_2').style.display='';
return;
}
if($('manager_3').style.display =='none' && num>2){
$('manager_3').style.display='';
return;
}
if($('manager_4').style.display =='none' && num>3){
$('manager_4').style.display='';
return;
}
if($('manager_5').style.display =='none' && num>4){
$('manager_5').style.display='';
return;
}
}
//
//Update balance on list in department
//
function show_up_balance(dept_id,balance){
$(dept_id).innerHTML=balance;
//BetterInnerHTML(document.getElementById(dept_id), balance); 
}
//
//To department tab wen campany saved with "has department" option
//
function createdeptmenu(obj,url,cid,action) {
	var valid=checkAllFields(obj);
	
	if(valid==false)
	return ;
	else{
	var post_data=formatPostData('save_contact_general','','add_company');
	var comp_id = returSynAjaxResult(url, post_data, "false");
	buttonDo(obj, '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=cust_mngt&company_id='+ comp_id +'&cust_enable=1&customer_id='+cid+'&ecom_pro_ind=E', '', 'special_links', 'true', 'Please Wait', 'o');
	
	if(action=='add'){
	buttonDo(obj, '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=new_user_dl&cust_enable=1&action=add', '', 'output_div', 'true', 'Please Wait', 'o');
		}else{
		buttonDo(obj, '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=new_user_dl&cust_enable=1&action=edit', '', 'output_div', 'true', 'Please Wait', 'o');
		}
	}
}
//
//to check value is numeric or not
//
function IsNumeric(val) {

    if (isNaN(parseFloat(val))) {

          return false;

     }

     return true

}

function textvisible(obj,id){
    
    if($(obj.id).selectedIndex == 1){
        $(id).style.display='';
        $('input11').setAttribute("class", "reqd");
        
    }else{
           
          $(id).style.display='none';
          $('input11').setAttribute("class", "");
          BetterInnerHTML($('sinput11'), ""); 
    }
    
}

function textvisible_shipping(obj,id){
    
    if($(obj.id).selectedIndex == 1){
        $(id).style.display='';
        $('input12').setAttribute("class", "reqd");
        
    }else{
           
          $(id).style.display='none';
          $('input12').setAttribute("class", "");
		  //var id_new="s".id;
          BetterInnerHTML($('sinput12'), ""); 
    }
    
}
function loginPwdEnable(obj)
{
   if(obj.checked)
   {
       document.getElementById('user_name').disabled=false;
	   document.getElementById('password_reset').style.display="block";
	   allInputs=document.getElementsByTagName('input');
	   for(i=0;i<allInputs.length;i++)
	   {
	      if(allInputs[i].className.indexOf('neqd')!=-1)
		  {
		   allInputs[i].className='reqd';
		  }
		  if(allInputs[i].id.indexOf('user_name')!=-1)
		  {
		  //existingClass=allInputs[i].className;
		  allInputs[i].className="reqd "+"loginid_validation";
		  }
	   }
	   allSelect=document.getElementsByTagName('select');
	   for(i=0; i<allSelect.length;i++)
	   {
	      if(allSelect[i].className.indexOf('neqd')!=-1)
		  {
		  allSelect[i].className='reqd';
		  }
	
	   }
   }
   else
   {
   document.getElementById('user_name').disabled=true;
   document.getElementById('password_reset').style.display="none";
   allInputs=document.getElementsByTagName('input');
	   for(i=0;i<allInputs.length;i++)
	   {
	      if(allInputs[i].className.indexOf('reqd')!=-1)
		  {
		   allInputs[i].className='neqd';
		  }
		  	   if(allInputs[i].id.indexOf('user_name')!=-1)
		  {
		 // existingClass=allInputs[i].className;
		  allInputs[i].className="neqd "+"loginid_validation";
		  }
	   }
	   allSelect=document.getElementsByTagName('select');
	   for(i=0; i<allSelect.length;i++)
	   {
	      if(allSelect[i].className.indexOf('reqd')!=-1)
		  {
		  allSelect[i].className='neqd';
		  }
	   }
	   
   }
}


function textverify(obj,id,con,company_id){
 //  alert('hiii');if($(obj.id).selectedIndex == 1)
 if(con=="sb"){
  //   alert("select box");
     var ptype = $(obj.id).selectedIndex;
    var pname = String( $(obj.id).options[ptype].getAttribute('type'));
    var post_data='address_id='+pname+'&company_id='+company_id;

  //   getPHP('/dealer_mngt/route_request.php?request=shipping_address_new_list',post_data,'input3');
     var address_list= returSynAjaxResult('/dealer_mngt/route_request.php?request=shipping_address_new_list', post_data, "true");
     $('input3').innerHTML = address_list;
    if($(obj.id).selectedIndex > 0){
        
        var ptype1 = $(obj.id).selectedIndex;
              var pname1 = String( $(obj.id).options[ptype1].getAttribute('type'));
          $(id).setAttribute("class", "");
           var post_data1='add_shipping_address='+pname1;
           var address= returSynAjaxResult('/dealer_mngt/route_request.php?request=shipping_address', post_data1, "true");
         //getPHP('/dealer_mngt/route_request.php?request=shipping_address',post_data1,'linput4');
     //    alert("select box index if"+address);
          $('linput5').innerHTML = "Shipping Address";
           $('linput4').innerHTML = address;
    }else{
         //   alert("select box else empty");
           
     
          $(id).setAttribute("class", "reqd");
          $(obj.id).setAttribute("class", "");
            $('linput4').innerHTML = "";
            $('linput5').innerHTML = "";
		  //var id_new="s".id;
         // BetterInnerHTML($('sinput12'), ""); 
    }
 //   alert($('input3').selectedIndex);
    if($('input3').selectedIndex < 1){
   //   alert("adress list empty");
         $('linput4').innerHTML = "";
            $('linput5').innerHTML = ""; 
    }
  
    
    } 
  else if(con=="ib"){
                  //   alert("Text box");
    if($(obj.id).value == '' || $(obj.id).value == null ){
                     //   alert("Text box :empty"+ $(obj.id).value);
          $(id).setAttribute("class", "reqd");
          $(obj.id).setAttribute("class", "");
    }else{
       //  alert("Text box :full"+ $(obj.id).value);
          $(id).setAttribute("class", "");
		  //var id_new="s".id;
         // BetterInnerHTML($('sinput12'), ""); 
    }
    }
    
}

function populateAddress(obj,id,id1){
    
     if($(obj.id).value == '' || $(obj.id).value == null ){
     //alert("populate_address if");
           $(id1).innerHTML = "";
            $(id).innerHTML = "";
     }else{
      // alert("populate_address else");
       var post_data='add_shipping_address='+$(obj.id).value;
        var address_list= returSynAjaxResult('/dealer_mngt/route_request.php?request=shipping_address', post_data, "true");
        $(id).innerHTML = address_list;
   // buttonDo($(obj.id), '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=shipping_address', '', id, 'true', 'Please Wait', 'o');
    $(id1).innerHTML = "Shipping Address";
    }
}

function textverifyuseother(obj,id,con){

 if(con=="sb"){
     
    if($(obj.id).selectedIndex > 0){
        
        
          $(id).setAttribute("class", "");
         
    }else{
      
          $(id).setAttribute("class", "reqd");
          $(obj.id).setAttribute("class", "");
         
    }

    
    } 
  else if(con=="ib"){
              
    if($(obj.id).value == '' || $(obj.id).value == null ){
                   
          $(id).setAttribute("class", "reqd");
          $(obj.id).setAttribute("class", "");
    }else{
   
          $(id).setAttribute("class", "");
	
    }
    }
    
}
function disabledApprove(typeVal)
{
  if(typeVal=="buyer")
  {
   document.getElementById('approve_order').disabled=false;
   document.getElementById('limit_line_item').disabled=false;
   document.getElementById('limit_order').disabled=false;
   }
  else
  {
  document.getElementById('approve_order').disabled=true;
  document.getElementById('limit_line_item').disabled=true;
  document.getElementById('limit_order').disabled=true;
  document.getElementById('approve_order').value="";
  document.getElementById('limit_line_item').value="";
  document.getElementById('limit_order').value="";
  }
  if((typeVal=="buyer")||(typeVal=="sbuyer"))
  {
   document.getElementById('department_id').style.display='block';
   document.getElementById('ldepartment_id').style.display='block';
  }
  else
  {
  document.getElementById('department_id').style.display='none';
  document.getElementById('ldepartment_id').style.display='none';
  }
}

function emailverify(obj,id,errid,con){
   if(con=="sb"){
     
    if($(obj.id).selectedIndex > 0){
                
          $(id).setAttribute("class", "");
            BetterInnerHTML($(errid), ""); 
            $(id).value = "";
    }else{
      
          $(id).setAttribute("class", "reqd email");
                  
    }

    
    } 
  else if(con=="ib"){
              
    if($(obj.id).value == '' || $(obj.id).value == null ){
                   
          $(id).setAttribute("class", "reqd");
           
    }else{
   
        buttonDo($(obj.id), '', 'ajax', 'n', '/dealer_mngt/route_request.php?request=email_contact_list', '', id, 'true', 'Please Wait', 'o');
	BetterInnerHTML($(errid), ""); 
        $(id).setAttribute("class", "");
    }
    }  
}


function textverifydepartment(obj,id,company_id){
    
    if($(obj.id).selectedIndex <1){
    var post_data='';
    var contact_list= returSynAjaxResult('/dealer_mngt/route_request.php?request=contact_list_empty', post_data, "true");
    $(id).innerHTML = contact_list;
    }else{
        var deptid=$(obj.id).value;
        var post_data='dept_id='+deptid+'&company_id='+company_id;
       var contact_list= returSynAjaxResult('/dealer_mngt/route_request.php?request=contact_list_department', post_data, "true");
       $(id).innerHTML = contact_list;
    }
  
}
function checkForQuoteName(quote_obj,obj) {
	if(document.getElementById(quote_obj).value=='') {
		document.getElementById('qerrormsg').innerHTML="Please enter quote name value.";
	}
	else {
		document.getElementById('qerrormsg').innerHTML="";
		quoteVal=document.getElementById(quote_obj).value;
		buttonDo(obj, '', 'ajax', 'n', 'route_request.php?request=save_quote&quote_name='+quoteVal, '', 'in_content', 'true', '', '');
		setTimeout('window.location="//"+top.location.host;',3000);
		
	}
}

function check_rule_creation(id,obj){
   
   if($(id).value==null || $(id).value==''){
   $('sinput1').innerHTML='Rule name required';
   return false;
   }
   else{
    $('sinput1').innerHTML='';
    buttonDo(obj,'' , 'ajax', 'n', '/dealer_mngt/route_request.php?request=rules_new_processing', '', 'output_div', 'true', '', '');
   }
}

function useCustomRule(val) {
	var newobj = $(val);

	if (val == 'custom_yes' && newobj.checked) {
		$('normal_rule').style.display='none';
		$('custom_rule').style.display='';
	}
	else if (val == 'custom_no' && newobj.checked) {
		$('normal_rule').style.display='';
		$('custom_rule').style.display='none';
	}
	else if (val == 'clear') {
		$('quick_sku').value='';
		$('price').value='';
	}
}
