_uacct = "UA-3838380-1";
urchinTracker();

function editCountryJS(url)
{
   opener=window.open( url, "myWindow", "status = 1,left=700, top=250, height = 300, width = 300, resizable = 0");
}

// used in product list
        function checkAllProduct(count)
        {
            chkId=document.getElementById('chkSelectAll');
            for(i=0;i<count;i++)
            {
                if(chkId.checked)
                    document.getElementById('chkProduct'+i).checked=true;
                else
                document.getElementById('chkProduct'+i).checked=false;
            }
        }
        
        
       
// used in tax class list
       function PopUpEditWindow()
        {
            var url="editTaxClass.php?taxClassId="+PopUpEditWindow.arguments[0];
            opener=window.open( url, "myWindow", "status = 1,left=700, top=250, height = 300, width = 300, resizable = 0" )

        }
        
// used in taxzone list
           function editTaxZoneJS(url)
           {
            
               opener=window.open( url, "myWindow", "status = 1,left=700, top=250, height = 300, width = 300, resizable = 0");

           }
           
           function postCountryJS()
           {
            document.formSelectCountry.submit();
           } 

// used in maintainManufacturer.php
function changeFormAction()
{

    document.getElementById('manufacturerPage').action=changeFormAction.arguments[0];
}



// used for category picker display
makeTreeLastNode = function () {
    if(document.getElementById('tree')!=null)
    {
        var tree = document.getElementById("tree");
        var lists = [ tree ];

        for (var i = 0; i < tree.getElementsByTagName("ul").length; i++)
          lists[lists.length] = tree.getElementsByTagName("ul")[i];

        for (var i = 0; i < lists.length; i++)
        {   var item = lists[i].lastChild;
            while (!item.tagName || item.tagName.toLowerCase() != "li")
               item = item.previousSibling; item.className += " last"; 
        }
        //loadCategoryPicker();
     }
};


// used for category picker display
makeTreeLastNodeSC = function () {
    if(document.getElementById('tree_s')!=null)
    {
        var tree = document.getElementById("tree_s");
        var lists = [ tree ];

        for (var i = 0; i < tree.getElementsByTagName("ul").length; i++)
          lists[lists.length] = tree.getElementsByTagName("ul")[i];

        for (var i = 0; i < lists.length; i++)
        {   var item = lists[i].lastChild;
            while (!item.tagName || item.tagName.toLowerCase() != "li")
               item = item.previousSibling; item.className += " last"; 
        }
        //loadCategoryPicker();
     }
};





function hidediv()
{
    if (document.getElementById('tree_view'))
    {
          document.getElementById('tree_view').style.visibility = 'hidden';
          document.getElementById('search_input').disabled=false;
    }
}



function show()
{
    if (document.getElementById('tree_view'))
    {
        
        document.getElementById('tree_view').style.visibility = 'visible';
        document.getElementById('search_input').disabled=true;

    }

}

function hidediv1()
{
    if (document.getElementById('tree_view'))
    {
          document.getElementById('tree_view').style.visibility = 'hidden';
          document.getElementById('cat_parentname').disabled=false;
    }
}



function show1()
{
    if (document.getElementById('tree_view'))
    {
        
        document.getElementById('tree_view').style.visibility = 'visible';
        document.getElementById('cat_parentname').disabled=true;

    }

}



/*---------------------------- CATEGORY PICKER FUNCTION FOR SEC CATEGORY----------------------------------*/
function hideDivSecCat()
{
    if (document.getElementById('sec_cat_tree_view'))
    {
          document.getElementById('sec_cat_tree_view').style.visibility = 'hidden';
          document.getElementById('secCatID').disabled=false;
    }
}



function showSecCat()
{ 
    if (document.getElementById('sec_cat_tree_view'))
    {
        document.getElementById('sec_cat_tree_view').style.visibility = 'visible';
      if(document.getElementById('cat_tree_view'))
        document.getElementById('cat_tree_view').style.visibility = 'hidden';
        document.getElementById('secCatID').disabled=true;
     if(document.getElementById('CatID'))
        document.getElementById('CatID').disabled=false;
    }

}

function loadCategoryPickerForSecCat()
{   
   
    var getEls=document.getElementsByClassName('m_active_s');

    for ( z=0; z<getEls.length; z++) 
    {
        getEls[z].style.cursor='pointer';
        getEls[z].style.color='black';
        getEls[z].onclick=function() 
                          { 
                            document.getElementById('secCatID').value=this.getAttribute('title');
                            document.getElementById('scid').value=this.getAttribute('code');
                            document.getElementById('sec_cat_tree_view').style.visibility = 'hidden';
                            document.getElementById('secCatID').disabled=false;
                          }
    }    
}

/*---------------------------------------------------------------------------------------------------------*/  


/*---------------------------- CATEGORY PICKER FUNCTION FOR SEC CATEGORY----------------------------------*/
function hideDivPromotion()
{
    if (document.getElementById('sec_cat_tree_view'))
    {
          document.getElementById('sec_cat_tree_view').style.visibility = 'hidden';
          document.getElementById('txtCategory').disabled=false;
    }
}



function showPromotion()
{ 
    if (document.getElementById('sec_cat_tree_view'))
    {
        document.getElementById('sec_cat_tree_view').style.visibility = 'visible';
        document.getElementById('txtCategory').disabled=true;
    }

}

function loadCategoryPickerForPromotion()
{   
   
    var getEls=document.getElementsByClassName('m_active_s');

    for ( z=0; z<getEls.length; z++) 
    {
        getEls[z].style.cursor='pointer';
        getEls[z].style.color='black';
        getEls[z].onclick=function() 
                          { 
                            document.getElementById('txtCategory').value=this.getAttribute('title');
                            document.getElementById('scid').value=this.getAttribute('code');
                            document.getElementById('sec_cat_tree_view').style.visibility = 'hidden';
                            document.getElementById('txtCategory').disabled=false;
                          }
    }    
}

/*---------------------------------------------------------------------------------------------------------*/  
/*---------------------------- CATEGORY PICKER FUNCTION FOR CATEGORY----------------------------------*/
function hideDivCat()
{
    if (document.getElementById('cat_tree_view'))
    {
          document.getElementById('cat_tree_view').style.visibility = 'hidden';
          document.getElementById('CatID').disabled=false;

    }
}



function showCat()
{
    if (document.getElementById('cat_tree_view'))
    {  
        document.getElementById('cat_tree_view').style.visibility = 'visible';
     if(document.getElementById('sec_cat_tree_view'))
        document.getElementById('sec_cat_tree_view').style.visibility = 'hidden';
        document.getElementById('CatID').disabled=true;
     if(document.getElementById('secCatID'))
        document.getElementById('secCatID').disabled=false;

    }

}

function loadCategoryPickerForCat()
{   
   
    var getEls=document.getElementsByClassName('m_active');

    for ( z=0; z<getEls.length; z++) 
    {
        getEls[z].style.cursor='pointer';
        getEls[z].style.color='black';
        getEls[z].onclick=function() 
                          { 
                            document.getElementById('CatID').value=this.getAttribute('title');
                            document.getElementById('cid').value=this.getAttribute('code');
                            document.getElementById('cat_tree_view').style.visibility = 'hidden';
                            document.getElementById('CatID').disabled=false;
                          }
    }    
}

/*---------------------------------------------------------------------------------------------------------*/   

 /*------------------------------ used in search page ---------------------------------------------------*/  
   function loadCategoryPickerForCatCHK()
   {   
      
       var getEls=document.getElementsByClassName('m_active');
   
       for ( z=0; z<getEls.length; z++) 
       {
           getEls[z].style.cursor='pointer';
           getEls[z].style.color='black';
         
       }    
}
            
/* select the category and insert to textbox */

function sele()
{
     document.getElementById('search_input').value= document.getElementById(sele.arguments[0]).firstChild.data;
     document.getElementById('tree_view').style.visibility = 'hidden';
}

function changeFormsAction(formId,actionPage)
{
    document.getElementById(formId).action=actionPage;

}
  
function validate()
{
    var valid="false";
    var nbrOfElmnts                = document.getElementById('listProducts2').elements.length;
    for( i=0; i< nbrOfElmnts; i++ )
    {
           var type                   = document.getElementById('listProducts2').elements[i].type;
           if( type == 'checkbox')
           {
               if (document.getElementById('listProducts2').elements[i].checked == true && document.getElementById('listProducts2').elements[i].id != 'chkSelectAll')
                  return true;
           }
     }
     alert("Please select a product");
     return false;

}


//window.onload = function()
function loadCategoryPicker()
{   

    var getEls=document.getElementsByClassName('m_active');

    for ( z=0; z<getEls.length; z++) 
    {
        getEls[z].style.cursor='pointer';
        getEls[z].style.color='black';
        getEls[z].onclick=function() 
                          { 
                            document.getElementById('search_input').value=this.getAttribute('title');
                            document.getElementById('scid').value=this.getAttribute('code');
                            document.getElementById('tree_view').style.visibility = 'hidden';
                            document.getElementById('search_input').disabled=false;
                          }
    }
}

document.getElementsByClassName = function(cl) 
{
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) 
    {
        var classes = elem[i].className;
        if (myclass.test(classes)) 
            retnode.push(elem[i]);
    }
    return retnode;
}; 


function loadCategoryPickerForCategory()
{   
   
    var getEls=document.getElementsByClassName('m_active');

    for ( z=0; z<getEls.length; z++) 
    {
        getEls[z].style.cursor='pointer';
        getEls[z].style.color='black';
        getEls[z].onclick=function() 
                          { 
                            document.getElementById('cat_parentname').value=this.getAttribute('title');
                            document.getElementById('cat_parent').value=this.getAttribute('code');
                            document.getElementById('tree_view').style.visibility = 'hidden';
                            document.getElementById('cat_parentname').disabled=false;
                          }
    }    
}


function addEvent(obj, evType, fn){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    return false;
  }
 }
 
 addEvent(window, 'load', stuHover);



/*----------------Javascript for validations -------------------*/

/* Validations
// Title: Tigra Form Validator */

// form fields description structure

var manufacture_fields  =   {
                                'manufacturer_name' :{'l':'Manufacturer Name','r':true}
                                

                            } 


o_config                =   {
                                'to_disable' : ['Submit', 'Reset'],
                                'alert' : 1
                            }
                            
var listProductsSC_fields      
                        =   {
                                'search_input' :{'l':'Category','r':true}
                            }

var addShoppingCart_fields  
                    =   {
                        'qty'  :{'l':'Quantity','r':true,'f':'integer'}
                        }

var addProducts_fields 
            =   {
                'txtProductName' :{'l':'Product Name','r':true} ,
                 CatID           :{'l':'Category','r':true},
                'txtMaxOrderQty' :{'l':'Maximum Order','f':'integer'},
                'txtMinOrderQty' :{'l':'Minimum Order','f':'integer'},
                'txtQtyOnHand'   :{'l':'Quantity on hand ','f':'integer'},
                'txtRetailPrice' :{'l':'Retail Price','f':'integer'}
                    }
               
var productList_fields  
            =   {
                'CatID'    :{'l':'Primary Category','r':true}
                }
            
var secproductList_fields
            =   {
                'secCatID'    :{'l':'Secondary Category','r':true}
                }
               
var productSearch_fields    ={
                    'txtProductFrom' :{'l':'Price Range From','f':'integer'},
                    'txtProductTo' :{'l':'Price Range To','f':'integer'}
                 }
            
var addBillingInfo_fields

            =   {
                    'txtCardNumber' : {'l':'Card number','r':true,'t':'lblCardNumber','c':'#7B9BB2'},
                    'lstCardType'   : {'l':'Card Type','r':true,'t':'lblCardType','c':'#7B9BB2'},
                    'txtCVN'        : {'l':'CVN','r':true,'f':'integer','t':'lblCardVn','c':'#7B9BB2'},
                    'txtName'       : {'l':'Name','r':true,'t':'lblName','c':'#7B9BB2'},
                    'txtAddr1'      : {'l':'Address Line 1','r':true,'t':'lblAddr1','c':'#7B9BB2'},
                    'txtCity'       : {'l':'City','r':true,'t':'lblCity','c':'#7B9BB2'},
                    'txtState'      : {'l':'State','r':true,'t':'lblState','c':'#7B9BB2'},
                    'lstCountry'    : {'l':'Country','r':true,'t':'lblCountry','c':'#7B9BB2'},
                    'txtZip'        : {'l':'ZipCode','r':true,'t':'lblPostalCode','c':'#7B9BB2'}                      
                }
var a_fields            =   {
                                'cusEmailID'            :{'l':'UserName','r':true,'f':'email','t':'sp_usr','c': '#5795CE'},
                                'cusPassword'            :{'l':'Password','r':true,'t':'sp_pwd','c': '#5795CE'}

                            }
                          
                            
// script for  checking the user entered fields.

var contact_fields   =  {
                        'cusLastName'           :{'l':'Last Name','r':true,'t':'sp_cusLastName','c':'#7B9BB2'},
                        'cusFirstName'          :{'l':'First Name','r':true,'t':'sp_cusFirstName','c':'#7B9BB2'},
                        'adrAddressLine1'       :{'l':'Address Line 1','r':true,'t':'sp_adrAddressLine1','c':'#7B9BB2'},
                        'adrCity'               :{'l':'City','r':true,'t':'sp_adrCity','c':'#7B9BB2'},
                        'adrState'              :{'l':'State','r':true,'t':'sp_adrState','c':'#7B9BB2'},
                        'adrPostalCode'         :{'l':'Zipcode','r':true,'t':'sp_adrPostalCode','c':'#7B9BB2'},
                        'cusTelephone'          :{'l':'Phone','r':true,'t':'sp_cusTelephone','c':'#7B9BB2'}
                       }

var promotion_fields   = {
                            'txtSaleName'       :{'l':'Sale Name','r':true},
                            'txtDateFrom'       :{'l':'Date From','r':true},
                            'txtDateTo'         :{'l':'Date To','r':true},
                            'txtCategory'       :{'l':'Category','r':true},
                            'txtDiscount'       :{'l':'Discount','r':true,'f':'integer'}
                         }

var password_fields                     =  {
                        'cusPassword'           :{'l':'New Password','r':true,'t':'sp_cusPassword','c':'#7B9BB2'},
                        'confirmPassword'       :{'l':'Confirm password','r':true,'m':'cusPassword','t':'sp_confirmPassword','c':'#7B9BB2'}
                       }




o_config                                =  {
                        'to_disable'            : ['Submit', 'Reset'],
                        'alert' : 1
                       }


// validator constructor call
var passwordValidator                   = new validator('passwordForm', password_fields, o_config);
var contactValidator                    = new validator('contactForm', contact_fields, o_config);
    
// validator constructor call
var manufacturerValidator     = new validator('manufacturerPage',manufacture_fields, o_config);
var listProductsSCValidator   = new validator('listProducts',listProductsSC_fields, o_config);
var addShoppingCartValidator  = new validator('m_submit', addShoppingCart_fields , o_config);
var productAddValidator       = new validator('frmProductAdd',addProducts_fields,o_config);
var productListValidator      = new validator('formProductList',productList_fields,o_config);
var productListSCValidator    = new validator('formProductList',secproductList_fields,o_config);
var priceRangeValidator       = new validator('formProductSearch',productSearch_fields,o_config);
var addBillingInfoValidator   = new validator('frmBillingInfo',addBillingInfo_fields,o_config);
var loginValidator            = new validator('loginpage', a_fields, o_config);
var saleMakerValidator        = new validator('formSaleMaker',promotion_fields,o_config);

// regular expressions or function to validate the format 

var re_dt = /^(\d{1,2})\-(\d{1,2})\-(\d{4})$/,
re_tm     = /^(\d{1,2})\:(\d{1,2})\:(\d{1,2})$/,
a_formats = {
        'alpha'   : /^[a-zA-Z\.\-]*$/,
        'alphanum': /^\w+$/,
        'unsigned': /^\d+$/,
        'integer' : /^[\+\-]?\d*$/,
        'real'    : /^[\+\-]?\d*\.?\d*$/,
        'email'   : /^[\w-\.]+\@[\w\.-]+\.[a-z]{2,4}$/,
        'phone'   : /^[\d\.\s\-]+$/,
        'date'    : function (s_date) 
                {
                // check format
                if (!re_dt.test(s_date))
                return false;
                // check allowed ranges
                if (RegExp.$1 > 31 || RegExp.$2 > 12)
                return false;
                // check number of day in month
                var dt_test = new Date(RegExp.$3, Number(RegExp.$2-1), RegExp.$1);
                if (dt_test.getMonth() != Number(RegExp.$2-1))
                return false;
                return true;
                 },
        'time'    : function validate_time(s_time) 
                {
                // check format
                if (!re_tm.test(s_time))
                return false;
                // check allowed ranges
                if (RegExp.$1 > 23 || RegExp.$2 > 59 || RegExp.$3 > 59)
                return false;
                return true;
                 }
        },
a_messages = [
        'No form name passed to validator construction routine',
        'No array of "%form%" form fields passed to validator construction routine',
        'Form "%form%" can not be found in this document',
        'Incomplete "%n%" form field descriptor entry. "l" attribute is missing',
        'Can not find form field "%n%" in the form "%form%"',
        'Can not find label tag (id="%t%")',
        'Can not verify match. Field "%m%" was not found',
        '"%l%" is a required field',
        'Value for "%l%" must be %mn% characters or more',
        'Value for "%l%" must be no longer than %mx% characters',
        '"%v%" is not valid value for "%l%"',
        '"%l%" must match "%ml%"'
         ]


// validator counstruction routine

function validator(s_form, a_fields, o_cfg)
{
    this.f_error = validator_error;
    this.f_alert = o_cfg && o_cfg.alert
    ? function(s_msg)
    {
        alert(s_msg); return false
    }
    : function()
    {
        return false
    };
    // check required parameters
    if (!s_form)
    return this.f_alert(this.f_error(0));
    this.s_form     = s_form;

    if (!a_fields || typeof(a_fields) != 'object')
    return this.f_alert(this.f_error(1));
    this.a_fields   = a_fields;

    this.a_2disable = o_cfg && o_cfg['to_disable'] && typeof(o_cfg['to_disable']) == 'object'
    ? o_cfg['to_disable']
    : [];

    this.exec       = validator_exec;
}


// validator execution method

function validator_exec()
{

    var o_form = document.forms[this.s_form];
    if (!o_form)
        return this.f_alert(this.f_error(2));

    b_dom = document.body && document.body.innerHTML;

    // check integrity of the form fields description structure
    
    for (var n_key in this.a_fields)
    {

        // check input description entry
        this.a_fields[n_key]['n'] = n_key;
        if (!this.a_fields[n_key]['l'])
            return this.f_alert(this.f_error(3, this.a_fields[n_key]));
        o_input = o_form.elements[n_key];
        if (!o_input)
            return this.f_alert(this.f_error(4, this.a_fields[n_key]));
        this.a_fields[n_key].o_input = o_input;
    }

    // reset labels highlight
    
    if (b_dom)
        for (var n_key in this.a_fields)
            if (this.a_fields[n_key]['t'])
            {

                var s_labeltag = this.a_fields[n_key]['t'], e_labeltag = get_element(s_labeltag);
                
                var clr = 'black';
                if (this.a_fields[n_key]['c'])
                   clr = this.a_fields[n_key]['c'];
                
                if (!e_labeltag)
                    return this.f_alert(this.f_error(5, this.a_fields[n_key]));
                this.a_fields[n_key].o_tag = e_labeltag;

                // normal state parameters assigned here
                
                //e_labeltag.className = 'tfvNormal';
                this.a_fields[n_key].o_tag.style.color=clr;
            }

            // collect values depending on the type of the input
            
            for (var n_key in this.a_fields)
            {

                var s_value = '';
                o_input = this.a_fields[n_key].o_input;
                if (o_input.type == 'checkbox') // checkbox
                    s_value = o_input.checked ? o_input.value : '';
                else if (o_input.value) // text, password, hidden
                    s_value = o_input.value;
                else if (o_input.options) // select
                    s_value = o_input.selectedIndex > -1
                    ? o_input.options[o_input.selectedIndex].value
                    : null;
                else if (o_input.length > 0) // radiobuton
                    for (var n_index = 0; n_index < o_input.length; n_index++)
                        if (o_input[n_index].checked)
                        {
                            s_value = o_input[n_index].value;
                            break;
                        }
                        this.a_fields[n_key]['v'] = s_value.replace(/(^\s+)|(\s+$)/g, '');
            }

            // check for errors
    
            var n_errors_count = 0,
            n_another, o_format_check;
            for (var n_key in this.a_fields)
            {

                o_format_check = this.a_fields[n_key]['f'] && a_formats[this.a_fields[n_key]['f']]
                ? a_formats[this.a_fields[n_key]['f']]
                : null;

                // reset previous error if any
                this.a_fields[n_key].n_error = null;

                // check reqired fields
                if (this.a_fields[n_key]['r'] && !this.a_fields[n_key]['v'])
                {
                    this.a_fields[n_key].n_error = 1;
                    n_errors_count++;
                }
                // check length
                else if (this.a_fields[n_key]['mn'] && String(this.a_fields[n_key]['v']).length < this.a_fields[n_key]['mn'])
                {
                    this.a_fields[n_key].n_error = 2;
                    n_errors_count++;
                }
                else if (this.a_fields[n_key]['mx'] && String(this.a_fields[n_key]['v']).length > this.a_fields[n_key]['mx'])
                {
                    this.a_fields[n_key].n_error = 3;
                    n_errors_count++;
                }
                // check format
                else if (this.a_fields[n_key]['v'] && this.a_fields[n_key]['f'] && (
                    (typeof(o_format_check) == 'function'
                    && !o_format_check(this.a_fields[n_key]['v']))
                    || (typeof(o_format_check) != 'function'
                    && !o_format_check.test(this.a_fields[n_key]['v'])))
                    )
                {
                    this.a_fields[n_key].n_error = 4;
                    n_errors_count++;
                }
                // check match
                else if (this.a_fields[n_key]['m'])
                {

                    for (var n_key2 in this.a_fields)
                        if (n_key2 == this.a_fields[n_key]['m'])
                        {
                            n_another = n_key2;
                            break;
                        }
                        if (n_another == null)
                            return this.f_alert(this.f_error(6, this.a_fields[n_key]));
                        if (this.a_fields[n_another]['v'] != this.a_fields[n_key]['v'])
                        {
                            this.a_fields[n_key]['ml'] = this.a_fields[n_another]['l'];
                            this.a_fields[n_key].n_error = 5;
                            n_errors_count++;
                        }
                }

    }

    // collect error messages and highlight captions for errorneous fields
    var s_alert_message = '',
    e_first_error;

    if (n_errors_count)
    {

        for (var n_key in this.a_fields)
        {

            var n_error_type = this.a_fields[n_key].n_error,
            s_message = '';

            if (n_error_type)
                s_message = this.f_error(n_error_type + 6, this.a_fields[n_key]);

            if (s_message)
            {
                if (!e_first_error)
                    e_first_error = o_form.elements[n_key];
                s_alert_message += s_message + "\n";
                
                // highlighted state parameters assigned here
                if (b_dom && this.a_fields[n_key].o_tag)
                //this.a_fields[n_key].o_tag.className = 'tfvHighlight';
                    this.a_fields[n_key].o_tag.style.color='red';

            }
        }
        alert(s_alert_message);
        // set focus to first errorneous field
        if (e_first_error.focus && e_first_error.type != 'hidden'  && !e_first_error.disabled)
            eval("e_first_error.focus()");
        // cancel form submission if errors detected
        return false;
    }

    for (n_key in this.a_2disable)
    if (o_form.elements[this.a_2disable[n_key]])
    o_form.elements[this.a_2disable[n_key]].disabled = true;

    return true;
}

function validator_error(n_index)
{

    var s_ = a_messages[n_index], n_i = 1, s_key;
    for (; n_i < arguments.length; n_i ++)
    for (s_key in arguments[n_i])
    s_ = s_.replace('%' + s_key + '%', arguments[n_i][s_key]);
    s_ = s_.replace('%form%', this.s_form);
    return s_;
}

function get_element (s_id)
{
    return (document.all ? document.all[s_id] : (document.getElementById ? document.getElementById(s_id) : null));
}



/*--------------------------- calender functions -----------------------------------*/
ReturnFunc = ''; 
function Calendar(iYear, iMonth, iDay, ContainerId, ClassName) 
{ 
    MonthNames = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); 
    //If no parameter is passed use the current date. 
    oDate = new Date(); 
    Year = (iYear == null) ? oDate.getFullYear() : iYear; 
    Month = (iMonth == null) ? oDate.getMonth() : iMonth - 1; 
    while(Month < 0){Month += 12;Year--} 
    while(Month >= 12){Month -= 12;Year++} 
    Day = (iDay == null) ? 0 : iDay; 
    oDate = new Date(Year, Month, 1); 
    NextMonth = new Date(Year, Month + 1, 1); 
    WeekStart = oDate.getDay(); 
    // Get the number of months in current month 
    MonthDays = Math.round((NextMonth.getTime() - oDate.getTime()) / 86400000) + 1; 
    // Check whether the Container Id is null 
    if(ContainerId != null) 
    { 
        ContainerId = ContainerId; 
        Container = document.getElementById(ContainerId); 
        // If an element doesnot exists with the given ContainerId then create it 
        if(!Container) 
            document.write('<div id="' + ContainerId + '">&nbsp;</div>'); 
    } 
    else 
    { 
        // Loop until a unique id is obtained for the container 
        do 
        { 
            ContainerId = 'tblCalendar' + Math.round(Math.random() * 1000); 
        } 
        while(document.getElementById(ContainerId)); 
        // create an element with the new id 
        document.write('<div id="' + ContainerId + '">&nbsp;</div>'); 
    } 
    Container = document.getElementById(ContainerId); 
    ClassName = (ClassName == null) ? 'tblCalendar' : ClassName; 
    HTML = '<table class="' + ClassName + '" cellspacing="0">'; 
    // Title bar 
    HTML += '<tr class="TitleBar"><td class="Nav"><a href="javascript:void(0)" onMouseDown="Calendar(' + Year + ', ' + Month + ', ' + Day+', \''+ContainerId+'\', \''+ClassName+'\');">&laquo;</a></td><td colspan="5" class="Title">' + MonthNames[Month] + ' ' + Year + '</td><td class="Nav"><a href="javascript:void(0)" onMouseDown="Calendar(' + Year + ', ' + (Month + 2) + ', ' + Day+', \''+ContainerId+'\', \''+ClassName+'\');">&raquo;</a></td></tr>'; 
    // Week Names 
    HTML += '<tr class="WeekName"><td>S</td><td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td></tr>'; 
    HTML += '<tr class="Days">'; 
    // Fill the previous month days with space 
    for(DayCounter = 0; DayCounter < WeekStart; DayCounter++) 
    { 
        HTML += '<td>&nbsp;</td>'; 
    } 
    // Populate current month 
      iDate     = new Date();
      
    for(DayCounter = 1; DayCounter < MonthDays; DayCounter++) 
    { 
        if((DayCounter + WeekStart) % 7 == 1) HTML += '<tr class="Days">'; 
        if(DayCounter == Day && iMonth==(iDate.getMonth()+1)) 
            HTML += '<td ><a href="javascript:ReturnDate(' + DayCounter + ')">' + DayCounter + '</a></td>'; 
        else HTML += '<td><a href="javascript:ReturnDate(' + DayCounter + ')">' + DayCounter + '</a></td>'; 
        if((DayCounter + WeekStart) % 7 == 0) HTML += '</tr>'; 
    } 
    // Fill the next month days with space 
    for(j = (42 - (MonthDays + WeekStart)), DayCounter = 0; DayCounter <= j; DayCounter++) 
    { 
        HTML += '<td>&nbsp;</td>'; 
        if((j - DayCounter) % 7 == 0) HTML += '</tr>'; 
    } 
   HTML += '<tr ><td colspan="7" style="background-color:#7EAFDA;"><a href="javascript:divClose()">CLOSE</a></td></tr></table></table>'; 
    Container.innerHTML = HTML; 
    // Returns Id of the element containing the calendar 
    return ContainerId; 
} 
function ReturnDate(Day) 
{ 
    SetDate(Day, Month+1, Year); 
    //window.close(); 
} 
function MakeDate(iYear, iMonth, iDay, fn) 
{ 
    D = new Date();
    Year = (typeof(iYear) != 'undefined') ? iYear : D.getFullYear(); 
    Month = (typeof(iMonth) != 'undefined') ? iMonth : D.getMonth(); 
    Day = (typeof(iDay) != 'undefined') ? iDay : D.getDate(); 
    ReturnFunc = fn; 
    id = Calendar(Year, Month, Day, 'cal', 'CalendarRed'); 
} 

function SelectDate(event)   // Called in the Onclick event of the calender image .Used to show the Calender
{  
// positioning of the calender
    posx=event.clientX;         
    posy=event.clientY;
    cID=document.getElementById('txtDateAvailable');
    div=document.getElementById("containerDiv");  
    div.style.position='absolute';
    div.style.left=630+"px";
    div.style.top=220+"px";
    div.style.display='block';

    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
    var D=cID.value;
    //check to see if the date is in the correct format
    if ( validateDate(D) ) {
        D = D.split('-');  
        alert(D);
    }
    else {
        Dat = new Date();
        D = new Array( Dat.getMonth()+1,Dat.getDate(), Dat.getFullYear());    // If invalid date then highlight the system date in the calender
    }

    MakeDate(D[2],D[0],D[1]);   // Used to display the calender
}

function SelectDate(selID,event)   // Called in the Onclick event of the calender image .Used to show the Calender
{  
// positioning of the calender
    posx=event.clientX;         
    posy=event.clientY;
    cID=document.getElementById(selID);
    div=document.getElementById("containerDiv");  
    div.style.position='absolute';
    div.style.left=posx+"px";
    div.style.top=posy+"px";
    div.style.display='block';

    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
    var D=cID.value;
    //check to see if the date is in the correct format
    if ( validateDate(D) ) {
        D = D.split('-');  
        alert(D);
    }
    else {
        Dat = new Date();
        D = new Array( Dat.getMonth()+1,Dat.getDate(), Dat.getFullYear());    // If invalid date then highlight the system date in the calender
    }

    MakeDate(D[2],D[0],D[1]);   // Used to display the calender
}    
function SetDate(Day, Month, Year)
{
    //  Sets the selected date value in the textbox
    cID.value=Year + '-' + Month+ '-' + Day; 
      
    document.getElementById("containerDiv").style.display="none";
}

// Check the passed value is a date value in the format 'mm/dd/yyyy'
 function validateDate( strValue ) { 
        var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
      
        //check to see if in correct format
        if(!objRegExp.test(strValue))
        return false; //doesnt match pattern, bad date
        else {
            var arrayDate = strValue.split('/');
            //create a lookup for months not equal to Feb.
            var arrayLookup = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
            var intDay = parseInt(arrayDate[1],10);
        
        //check if month value and day value agree
        if( arrayLookup[arrayDate[0]-1] != null) {
          if(intDay <= arrayLookup[arrayDate[0]-1] && intDay != 0)
            return true; //foud in lookup table, good date
        }

        //check for February 
        var intMonth = parseInt(arrayDate[0],10);
        if (intMonth == 2) {
           var intYear = parseInt(arrayDate[2]);
           if (intDay > 0 && intDay < 29) {
               return true;
           }
           else if (intDay == 29) {
             if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
                 (intYear % 400 == 0)) {
                  // year div by 4 and ((not div by 100) or div by 400) ->ok
                 return true;
             }
           }
        }
      }
      return false; //any other values, bad date
 }
 
function divClose()
{
 document.getElementById("containerDiv").style.display="none";
}

/* ---------- Form submitting functions ------------------ */

/* Function to submit search information. */

function submitProductList(pageNumber,searchFlg,searchValue)
{
     if ( searchFlg == 'C' )
     {
        document.forms['m_submit'].category.value        = searchValue;
     }
     else ( searchFlg == 'S' )
     {
        document.forms['m_submit'].searchParm.value      = searchValue;
     }
     document.forms['m_submit'].currentPage.value   = pageNumber;
     document.forms['m_submit'].searchFlg.value     = searchFlg;
     document.forms['m_submit'].submit();
}

function searchByValue(searchFlg)
{
    
    location.href= document.getElementsByTagName('base')[0].href + 'b_listProduct/'+searchFlg+'/'+document.getElementById('searchParam').value;
}

function changeBase()
{
    document.getElementsByTagName('base')[0].href = "https://localhost/jalensky";
}

/* Function to submit shopping cart information */
function m_addToCart(productId,productListingNumber)
{
     
     document.forms['m_submit'].qty.value               = document.getElementById('txtQty_'+productListingNumber).value;
     var minimum_quantity                               = document.getElementById('minQty_'+productListingNumber).value;
     var maximum_quantity                               = document.getElementById('maxQty_'+productListingNumber).value;
     if(!addShoppingCartValidator.exec())
     {
        document.getElementById('txtQty_'+productListingNumber).value='';
        document.getElementById('txtQty_'+productListingNumber).focus();     
        return false;
     }
     if( eval(document.forms['m_submit'].qty.value) <= 0 )
     {
        alert('"Quantity" must be greater than "0"');
        document.getElementById('txtQty_'+productListingNumber).value='';
        document.getElementById('txtQty_'+productListingNumber).focus();
        return false;
     }
     if ( maximum_quantity == 0 )
     {
        maximum_quantity                                = 100;
     }
     if ( (  ( eval(document.forms['m_submit'].qty.value) < minimum_quantity ) || ( eval(document.forms['m_submit'].qty.value) > maximum_quantity) ) 
          
        )
     {
        alert('"Quantity" entered must be between "'+minimum_quantity + '" and "'+maximum_quantity + '"');
        document.getElementById('txtQty_'+productListingNumber).value='';
        document.getElementById('txtQty_'+productListingNumber).focus();      
        return false;
     }
     document.forms['m_submit'].productID.value         = productId;
     document.forms['m_submit'].salePrice.value         = document.getElementById('salePrice_'+productListingNumber).value;
     document.forms['m_submit'].retailPrice.value       = document.getElementById('retailPrice_'+productListingNumber).value;
     document.forms['m_submit'].productWeight.value     = document.getElementById('productWeight_'+productListingNumber).value;
     document.forms['m_submit'].taxClassID.value        = document.getElementById('taxClassID_'+productListingNumber).value;
     
     document.forms['m_submit'].action                  = 'b_addToCart.php';
     document.forms['m_submit'].submit();
     return true;
}


// functions used in shopping cart page
function m_removeProductJS(productId,productListingNumber)
{

     document.forms['m_submit'].qty.value               = document.getElementById('txtQty_'+productListingNumber).value;
     document.forms['m_submit'].salePrice.value         = document.getElementById('finalPrice_'+productListingNumber).value;
     document.forms['m_submit'].action                  = "removeItemFromCart.php";
     document.getElementById('productID').value         = productId;
     document.forms['m_submit'].submit();
}

// can remove; intended to use on continue shopping (back) clicking on shopping cart
function continueShoppingJS()
{
        if(!empty(document.forms['frmHiddenShopCart'].fromPage.value))
        {
             document.forms['frmHiddenShopCart'].submit();
        }
        else
        {
            document.forms['frmHiddenShopCart'].action.value ="index.php";
            document.forms['frmHiddenShopCart'].submit();
        }

}

// used in b_listProduct for paging
function setHiddenFieldJS(val)
{
   pgActionID = document.getElementById('pagingAction');
   pgActionID.value = val;
   document.getElementById('m_submit').submit();
}

// javascript for shippingInfo page
copyDataFrmContact = function ()
{
    if (document.getElementById('checkBox').checked == true )
    {
        var i=0;
        var len=document.getElementById('ordCustomerCountry').options.length;
        for (i=0;i<len; i++)
        { 
            if (document.getElementById('ordCustomerCountry').options[i].value == document.getElementById('hdeCustomerCountry').value)
            {
                document.getElementById('ordCustomerCountry').options[i].selected=true;    
            }
        }
    
        document.getElementById('ordCustomerName').value        = document.getElementById('hdeCustomerName').value;
        document.getElementById('ordCustomerAddrLine1').value   = document.getElementById('hdeCustomerAddrLine1').value;
        document.getElementById('ordCustomerAddrLine2').value   = document.getElementById('hdeCustomerAddrLine2').value;
        document.getElementById('ordCustomerCity').value        = document.getElementById('hdeCustomerCity').value;
        document.getElementById('ordCustomerState').value       = document.getElementById('hdeCustomerState').value;
        document.getElementById('ordCustomerPostCode').value    = document.getElementById('hdeCustomerPostCode').value;
        
        
    }


}


// functions for billing info page
function submit()
{
    document.getElementById('form_submitted').value="Y";
    document.getElementById('frmBillingInfo').submit();
}

function populateFieldWithValue(sourceField,destField)
{
    document.getElementById(destField).value=document.getElementById(sourceField).value;
}


function copyContactInfo()
{

    if ( document.getElementById('chkCopyShippingInfo') != null )
    {
        if(document.getElementById('chkCopyShippingInfo').checked)
            document.getElementById('chkCopyShippingInfo').checked = false;  
    }
            
            
    if (document.getElementById('chkCopyContactInfo').checked == true )
    {
    
        populateFieldWithValue('contact_name','txtName');
        populateFieldWithValue('contact_addr1','txtAddr1');
        populateFieldWithValue('contact_addr2','txtAddr2');
        populateFieldWithValue('contact_city','txtCity');
        populateFieldWithValue('contact_state','txtState');
        populateFieldWithValue('contact_country','lstCountry');
        populateFieldWithValue('contact_postal_code','txtZip');    
    }
    

}

function copyShippingInfo()
{
    
    if ( document.getElementById('chkCopyContactInfo') != null )
    {
        if(document.getElementById('chkCopyContactInfo').checked)
            document.getElementById('chkCopyContactInfo').checked = false;      
    }
        
    if (document.getElementById('chkCopyShippingInfo').checked == true )
    {
    
        populateFieldWithValue('shipping_name','txtName');
        populateFieldWithValue('shipping_addr1','txtAddr1');
        populateFieldWithValue('shipping_addr2','txtAddr2');
        populateFieldWithValue('shipping_city','txtCity');
        populateFieldWithValue('shipping_state','txtState');
        populateFieldWithValue('shipping_country','lstCountry');
        populateFieldWithValue('shipping_postal_code','txtZip');
    }
    
    
}
// end functions for billing info page

// function to call a popup when the password is forgotten
function forgotPassword()
{ 
    window.open('b_forgotPassword.php','mywindow','width=300,height=300,toolbar=no,location=no,left=600,top=200,resizable=no');
    return false;
}

function windowOpener(url, name, args) 
{
    var popupWin;
    url = 'http://www.jalenskysgreatlakes.com/' + url;
    if (typeof(popupWin) != "object") 
    { 
        popupWin = window.open(url,name,args);
    } 
    else 
    {
        if (!popupWin.closed)
        { 
            popupWin.location.href = url;
        } 
        else 
        { 
            popupWin = window.open(url, name,args);
        }
    }
    popupWin.focus();
}