function LuhnCheck(str){
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++){
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}


function validateCCNum(cardNum){
	var result = false;
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first2digs = cardNum.substring(0,2);
	var first3digs = cardNum.substring(0,3);
	var first4digs = cardNum.substring(0,4);
	var first5digs = cardNum.substring(0,5);
	var first6digs = cardNum.substring(0,6);
	
	
	//cascade validation
	//source: http://en.wikipedia.org/wiki/Credit_card_number
	for(i=0; i<11; i++){
		switch(i){
			case 0: //American Express 34 and 37 15 
				result = (cardLen == 15) && ((first2digs == "34") || (first2digs == "37"));
				break;
			case 1: //Bankcard 560–561 16 
				result = (cardLen == 16) && ((first3digs == "560") || (first3digs == "561"));
				break;
			case 2: //Diners Club International[1] 36 15 
				result = (cardLen == 15) && (first2digs == "36");
				break;
			case 3: //Diners Club US & Canada[1] 55 16 
				result = (cardLen == 16) && (first2digs == "55");
				break;
			
			//As of October 1st, 2005, Discover Bank will include a new BIN in the range of 650000–650999.
			case 4: //Discover Card 6011 and 650* 16 
				result = (cardLen == 16) && ((first3digs == "650") || (first4digs == "6011"));
				break;
			case 5: //JCB 3 16 
				result = (cardLen == 16) && (firstdig == "3");
				break;
			case 6: //JCB 1800 and 2131 15 
				result = (cardLen == 15) && ((first4digs == "1800") || (first4digs == "2131"));
				break;
				
			//As of November 8, 2004, MasterCard purchased the domestic (US) Diner's Club BIN range.
			//Diner's club international's website makes no reference to old 38 prefix numbers,
			//and they can be presumed reissued under the 55 or 36 BIN prefix
			case 7: //MasterCard* 51–55, 36 14 or 16 
				result = ((cardLen == 14) || (cardLen == 16)) && ((first2digs == "36") || (first2digs == "51") || (first2digs == "52") || (first2digs == "53") || (first2digs == "54") || (first2digs == "55") || (first2digs == "56") || (first2digs == "57")||(first2digs == "58") || (first2digs == "38"));
				break;
			case 8: //Visa 4 13 or 16 	
				result = ((cardLen == 13) || (cardLen == 16)) && (firstdig == "4");
				break;
			case 9: //Solo (debit card)
				result = ((cardLen == 16) || (cardLen == 18) || (cardLen == 19)) && (first4digs == "6334" || first4digs == "6767");
				break;
			case 10: //Switch (debit card)
				result = ((cardLen == 16) || (cardLen == 18) || (cardLen == 19)) && (first4digs == "4903" || first4digs == "4905" || first4digs == "4911" || first4digs == "4936" || first4digs == "6333" || first4digs == "6759" || first6digs == "564182" || first6digs == "633110");
				break;
		}
		if(result) return true;
	}
	return false;
}

// checks if the card is expired
function isCardExpired (expMonth, expYear) {
	var expDate = new Date();
	expDate.setFullYear(expYear,expMonth - 1,1);
	var today = new Date();
	today.setFullYear(today.getFullYear(),today.getMonth(),1);
	if (expDate < today)
	{
		return true;
	}
	return false;
}

function validateExpDate(expDate){
	//valid are  mmyy, mm/yy, mm20yy, mm/20yy
	var rex = /^(([0]\d{1})|([1]([012])))(\/?)(([2][0])?)(\d{2})$/;
	return rex.test(expDate);
}

function validateExpMonth(expDate){
	//valid are  01-12
	var rex = /^(([0]?\d{1})|([1]([012])))$/;
	return rex.test(expDate);
}

function validateExpYear(expDate){
	//valid are  mmyy, mm/yy, mm20yy, mm/20yy
	var rex = /^(([2][0])?)(\d{2})$/;
	return rex.test(expDate);
}

function validateCVC2(cvc2){
   frm = document.getElementById("frmPayment");
   ccType = frm.elements['form[cc_type]'].value;
   
   if (ccType == 'VISA' || ccType == 'MC') {
       var rex = /^(\d{3})$/;
       return rex.test(cvc2);
   }
   else {
       //valid are ddd or dddd
       var rex = /^(\d{3,4})$/;
       return rex.test(cvc2);
   }   
    
	
}

function validateName(name){
	var rex = /^[a-zA-Z \-\']+$/;
	return rex.test(name);
}

function validateText(txt){
	var d = "";
	for(i=0; i < txt.length; i++){
		if(txt.charAt(i) != " "){
			d = d + txt.charAt(i);
		}
	}
	if(d == ""){
		return false;
	}
	else{
		return true;
	}
}

function CheckField(frm, fname, ftitle){
	var s = frm.elements[fname].value;
	var d = "";
	
	for(i=0; i < s.length; i++){
		if(s.charAt(i) != " "){
			d = d + s.charAt(i);
		}
	}
	if(d == ""){
		alert(msg_please_enter + ' ' + ftitle);
		frm.elements[fname].focus();
		return false;
	}
	else{
		return true;
	}
}

function CheckCustomFields(frm, place){
	var irex = /^custom_field\[(\d{1,})\]$/;
	for(i=0; i<frm.elements.length; i++){
		if(irex.test(frm.elements[i].name)){
		//	alert(frm.elements[i].name);
			var s = frm.elements[i].name;
			var id = s.substring(13, s.length-1);
			if(frm.elements['custom_field_place[' + id + ']'].value == place){
				if(frm.elements['custom_field_required[' + id + ']'].value == 'yes'){
					//alert(frm.elements[i].type);
					if(frm.elements[i].type == "checkbox" && !frm.elements[i].checked){
						alert(msg_to_continue_please_check + ' ' + frm.elements['custom_field_name[' + id + ']'].value);
						frm.elements[i].focus();
						return false;
					}
					else if(frm.elements[i].value == ""){
						alert(msg_please_enter + ' ' + frm.elements['custom_field_name[' + id + ']'].value);
						frm.elements[i].focus();
						return false;
					}
				}
			}
		}
	}
	return true;
}

function CheckAddProduct(frm, min_order, max_order, allowed_max){ 
    if(product_may_be_added){      
		var order_quantity = document.getElementById('order_quantity');
        if(order_quantity.value > 0)
        {
            var allowed_max = allowed_max - order_quantity.value;
        }
        var user_type = document.getElementById('user_type').value; 
        if(user_type=='Special')
        {
             var allowed_max = '-'; 
        }
        var rex = /^(\d{1,})$/
		if(!rex.test(frm.elements["oa_quantity"].value)){
			alert(msg_enter_numeric_product_quantity);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		if((frm.elements["oa_quantity"].value *1) < min_order){
			alert(msg_number_of_items_exceeded_min);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		if((max_order != "-") && (frm.elements["oa_quantity"].value * 1 > max_order)){
			alert(msg_number_of_items_exceeded_max);
			frm.elements["oa_quantity"].focus();
			return false;
		}
		if((allowed_max != "-") && (frm.elements["oa_quantity"].value * 1 > allowed_max)){
			 var productsku = frm.elements["oa_id"].value;
             if(allowed_max==0)
             {
                displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We don\'t have that many items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false 
                //var answer = confirm('Very sorry.  We only have no more items in stock.\nWould you like to request more ?');
             }
             else
             {
                displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We only have '+ allowed_max +' items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false
               // var answer = confirm('Very sorry.  We only have '+ allowed_max +' items in stock.\nWould you like to request more ?');
             }
             /*if(answer)
                {
                       emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
                }*/
           // alert(msg_number_of_items_exceed_inventory);
			frm.elements["oa_quantity"].focus();
			return false;
		}
        return true;
	}
	return false;
}
var globalfrm  = '';
function CheckAddProductAttribute(frm, min_order, max_order, allowed_max){ 
    if(product_may_be_added){
        globalfrm = frm;
        var product_quantity = document.getElementById('product_stock');
        var product_stock = product_quantity.innerHTML;
        var prd = product_stock.split(" ");
        allowed_max = prd[0];
        var user_type = document.getElementById('user_type').value; 
        if(user_type=='Special')
        {
             var allowed_max = '-'; 
        } 
        var rex = /^(\d{1,})$/
        if(!rex.test(frm.elements["oa_quantity"].value)){
            alert(msg_enter_numeric_product_quantity);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((frm.elements["oa_quantity"].value *1) < min_order){
            alert(msg_number_of_items_exceeded_min);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((max_order != "-") && (frm.elements["oa_quantity"].value * 1 > max_order)){
            alert(msg_number_of_items_exceeded_max);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((allowed_max != "-") && (frm.elements["oa_quantity"].value * 1 > allowed_max)){
             var productsku = frm.elements["oa_id"].value;
             if(allowed_max==0)
             {
                displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We don\'t have that many items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();product_attribute_verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false 
                //var answer = confirm('Very sorry.  We only have no more items in stock.\nWould you like to request more ?');
             }
             else
             {
                displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We only have '+ allowed_max +' items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();product_attribute_verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false
                //var answer = confirm('Very sorry.  We only have '+ allowed_max +' items in stock.\n Would you like to request more ?');
             }
            /* if(answer)
                {
                       emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
                       xajax_processAjaxAction("getproductsubid",xajax.getFormValues(frm));
                } */
           // alert(msg_number_of_items_exceed_inventory);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        return true;
    }
    return false;
}
function product_attribute_verify(ver)
{
        var frm = globalfrm; 
        if(ver)
        {
             emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
             xajax_processAjaxAction("getproductsubid_in_product_detail_page",xajax.getFormValues(frm)); 
        }
}
function product_detail_page_attribute_verify(ver)
{
       var frm = document.frmAddItem;
        if(ver)
        {
             emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
             xajax_processAjaxAction("getproductsubid_in_product_detail_page",xajax.getFormValues(frm)); 
        }
}
function quick_order_attribute_verify(ver)
{
        var frm = globalfrm;
        if(ver)
        {
             emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
             var productsku = document.getElementById("form[productsku]");
             var productskuarr = frm.elements["oa_id"].value;
             productskuarr = productskuarr.split("#@#");
             var count = productskuarr.length;
             if(count > 2)
             {
                productid = productskuarr[1];
                //productid = productskuarr[0]+" - "+productskuarr[1];
                productsku.value = productid;
             }
             else
             {
                productid = productskuarr[0];
                productsku.value = productid;
             }   
        }
}
/* @desc code added by dinesh on 24-june-2010 for checking the username or email */
 function CheckResetPassword(frm){
	if(!CheckField(frm, "login", "username")) return false;
	return true;
}
function CheckResetPasswordemail(frm){
    if(!isEmail(frm.elements["email"].value)){
        alert(msg_enter_valid_email);
        frm.elements["email"].focus();
        return false;
    }
    return true;
}
/* End of code added by dinesh */

/*function CheckCartForm(frm){
	var irex = /^oa_quantity\[(\d{1,})\]$/;
	var prex = /^oa_pid_to_ocid\[(\d{1,})\]$/;
	var drex = /^(\d{1,})$/
	
	var products = new Array();
	
	for(i=0; i<frm.elements.length; i++){
		
		if(irex.test(frm.elements[i].name)){
			if(!drex.test(frm.elements[i].value)){
				alert(msg_enter_numeric_product_quantity);
				frm.elements[i].focus();
				return false;	
			}
			if(frm.elements[i].value * 1 < (frm.elements["min_" + frm.elements[i].name].value) * 1){
				alert(msg_number_of_items_exceeded_min);
				frm.elements[i].focus();
				return false;
			}
			if(
				(frm.elements["max_" + frm.elements[i].name].value != "-") && 
				(frm.elements[i].value * 1 > frm.elements["max_" + frm.elements[i].name].value * 1)
			){
				alert(msg_number_of_items_exceeded_max);
				frm.elements[i].focus();
				return false;
			}
			if(
				(frm.elements["allowed_" + frm.elements[i].name].value != "-") && 
				(frm.elements[i].value * 1 > frm.elements["allowed_" + frm.elements[i].name].value * 1)
			){
				alert(msg_number_of_items_exceed_inventory);
				frm.elements[i].focus();
				return false;
			}
		}
		
		if(prex.test(frm.elements[i].name)){
			var ocid = frm.elements[i].value;
			var pid = frm.elements["oa_ocid_to_pid[" + ocid + "]"].value;
			if(products[pid]){
				products[pid] = products[pid] + frm.elements["oa_quantity[" + ocid + "]"].value * 1;
			}
			else{
				products[pid] = frm.elements["oa_quantity[" + ocid + "]"].value * 1;
			}
			
			if(frm.elements["oa_inventory_control[" + ocid + "]"].value == "Yes"){
				if(frm.elements["allowed_oa_quantity[" + ocid + "]"].value < products[pid]){
					alert(msg_number_of_items_exceed_inventory);
					frm.elements["oa_quantity[" + ocid + "]"].focus();
					return false;
				}
			}
		}
	}
	return true;
}       */

/** function added by payal on 10-May to check for valid quantity on update cart **/
var cartpid=0;
var cartproduct_sub_id=0;
function CheckCartForm(frm, item_ocid ){
    
    var irex = /^oa_quantity\[(\d{1,})\]$/;
    var prex = /^oa_pid_to_ocid\[(\d{1,})\]$/;
    var drex = /^(\d{1,})$/
    var user_type = document.getElementById('user_type').value; 
                         
    var products = new Array();
    globalfrm = frm;  
    for(i=0; i<frm.elements.length; i++){    
        if(irex.test(frm.elements[i].name)){
            if (frm.elements[i].name == 'oa_quantity['+item_ocid+']') {
                if(!drex.test(frm.elements[i].value)){
                    alert(msg_enter_numeric_product_quantity);
                    frm.elements[i].focus();
                    return false;    
                }
                
                if(frm.elements[i].value * 1 < (frm.elements["min_" + frm.elements[i].name].value) * 1){
                    alert(msg_number_of_items_exceeded_min);
                    frm.elements[i].focus();
                    return false;
                }
                
                if(
                    (frm.elements["max_" + frm.elements[i].name].value != "-") && 
                    (frm.elements[i].value * 1 > frm.elements["max_" + frm.elements[i].name].value * 1)
                ){       
                    alert(msg_number_of_items_exceeded_max);
                    frm.elements[i].focus();
                    return false;
                }
               if(user_type!='Special')
               { 
                    if(
                        (frm.elements["allowed_" + frm.elements[i].name].value != "-") && 
                        (frm.elements[i].value * 1 > frm.elements["allowed_" + frm.elements[i].name].value * 1)
                    ){   
                        alert(msg_number_of_items_exceed_inventory);
                        frm.elements[i].focus();
                        return false;
                    }
               }     
            } 
        }
           
        if(prex.test(frm.elements[i].name)) { 
            var ocid = frm.elements[i].value;
            var pid = frm.elements["oa_ocid_to_pid[" + ocid + "]"].value;
            
            if (ocid == item_ocid) {  
                if(products[pid]){
                    products[pid] = products[pid] + frm.elements["oa_quantity[" + ocid + "]"].value * 1;
                }
                else{ 
                    products[pid] = frm.elements["oa_quantity[" + ocid + "]"].value * 1;
                }
                if(frm.elements["oa_inventory_control[" + ocid + "]"].value == "Yes"){
                    if(frm.elements["allowed_oa_quantity[" + ocid + "]"].value < products[pid]){  
                        if(user_type!='Special')
                        {
                                cartpid = frm.elements["oa_ocid_to_product_id[" + ocid + "]"].value;
                                displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We only have '+ frm.elements["allowed_oa_quantity[" + ocid + "]"].value +' items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();cart_product_attribute_verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false 
                                //alert(msg_number_of_items_exceed_inventory);
                                frm.elements["oa_quantity[" + ocid + "]"].focus();
                                return false;
                        } 
                    }
                }
                if((frm.elements["allowed_oa_quantity[" + ocid + "]"].value == "-") && (frm.elements["oa_product_sub_id[" + ocid + "]"].value !=''))
                    {
                        var oa_text = frm.elements[i].value;
                        var oa_qty = document.getElementById('oa_quantity['+oa_text+']');
                        
                        if(!drex.test(oa_qty.value))
                        {
                                alert(msg_enter_numeric_product_quantity);
                                oa_qty.focus();
                                return false;    
                         }
                         if(products[pid] * 1 < (1) * 1)
                         {
                              alert(msg_number_of_items_exceeded_min);  
                              oa_qty.focus();
                              return false;
                         }
                         if(user_type!='Special')
                         { 
                            cartpid = frm.elements["oa_ocid_to_product_id[" + ocid + "]"].value; 
                            cartproduct_sub_id = frm.elements["oa_product_sub_id[" + ocid + "]"].value;
                            prod_id =   frm.elements["oa_ocid_to_pid[" + ocid + "]"].value;
                            xajax_processAjaxAction("checkcartproducts",xajax.getFormValues(frm),prod_id,cartproduct_sub_id,products[pid],item_ocid);       
                            return false;
                         }   
                    }
            }
        }
    }
    
    
    if(document.getElementById('update_productID')) {
        document.getElementById('update_productID').value = item_ocid
    }    
    return true;
}               
/* end of function added by payal **/

function check_cart_product_attribute(allowed_max,request_qty,ocid)
{
     var frm = globalfrm;
     if(parseInt(request_qty) > parseInt(allowed_max))
     {
        displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We only have '+ allowed_max +' items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();cart_product_attribute_verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false
     }
     else
     {
         if(document.getElementById('update_productID')) 
         {
            document.getElementById('update_productID').value = ocid;
         }
         orderUpdateItems(); 
        //frm.submit();
        return true;
     }  
}

function cart_product_attribute_verify(ver)
   {
        var frm = globalfrm;  
        if(ver)
        {
             emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
             var productsku = document.getElementById("form[productsku]");
             if(cartproduct_sub_id !=0)
             {
                productsku.value = cartproduct_sub_id;
             }
             else
             {
                productsku.value = cartpid;
             }       
        }
   }
function CheckNewsletters(frm){
	if(!isEmail(frm.elements["email_address"].value)){
		alert(msg_enter_valid_email);
		frm.elements["email_address"].focus();
		return false;
	}
	return true;
}

function CheckUnsubscribe(frm){
	if(!isEmail(frm.elements["email_address"].value)){
		alert(msg_enter_valid_email);
		frm.elements["email_address"].focus();
		return false;
	}
	if(confirm(msg_want_cancel_subscription)){
		return true;
	}
	return false;
}

function CheckLoginForm(frm){
	if(!CheckField(frm, "login", msg_your_username)) return false;
	if(!CheckField(frm, "password", msg_your_password)) return false;
	return true;
}

/**
* Check tell a friend form
* Created By Kalarav on 7-June-2010
*/
function CheckTellFriendForm(frm){
	
    if(!CheckField(frm, "your_name", msg_your_yourname)) return false;
    
    var rexfirst = /^[a-zA-Z \-\' ]*$/
    if(!rexfirst.test(frm.elements["your_name"].value)){
            alert('Please enter valid first name');
            frm.elements["your_name"].focus();
            return false;
    }
        
	if(!CheckField(frm, "your_email", msg_email_address)) return false;
	if(!isEmail(frm.elements["your_email"].value)){
		alert(msg_enter_valid_email);
		frm.elements["your_email"].focus();
		return false;
	}

	if(!CheckField(frm, "to_email_1", msg_email_address)) return false;
	if(!isEmail(frm.elements["to_email_1"].value)){
		alert(msg_enter_valid_email + " in email 1");
		frm.elements["to_email_1"].focus();
		return false;
	}
	
	if(frm.elements["to_email_2"].value != "")
	{
		if(!isEmail(frm.elements["to_email_2"].value)){
			alert(msg_enter_valid_email + " in email 2");
			frm.elements["to_email_2"].focus();
			return false;
		}
	}

	if(frm.elements["to_email_3"].value != "")
	{
		if(!isEmail(frm.elements["to_email_3"].value)){
			alert(msg_enter_valid_email + " in email 3");
			frm.elements["to_email_3"].focus();
			return false;
		}
	}

	if(frm.elements["to_email_4"].value != "")
	{
		if(!isEmail(frm.elements["to_email_4"].value)){
			alert(msg_enter_valid_email + " in email 4");
			frm.elements["to_email_4"].focus();
			return false;
		}
	}

	if(frm.elements["to_email_5"].value != "")
	{
		if(!isEmail(frm.elements["to_email_5"].value)){
			alert(msg_enter_valid_email + " in email 5");
			frm.elements["to_email_5"].focus();
			return false;
		}
	}

	return true;
}

/////////////////////////////
// CHECK SIGNUP FORM
function CheckSignupForm(frm, fm_company, fm_address2, fm_phone, ship2all, ship2countries){
	if(!CheckField(frm, "form[fname]", msg_first_name)) return false;
    var rexfirst = /^[a-zA-Z \-\' ]*$/
    if(!rexfirst.test(frm.elements["form[fname]"].value)){
            alert('Please enter valid first name');
            frm.elements["form[fname]"].focus();
            return false;
        }
	if(!CheckField(frm, "form[lname]", msg_last_name)) return false;
	if(!rexfirst.test(frm.elements["form[lname]"].value)){
            alert('Please enter valid last name');
            frm.elements["form[lname]"].focus();
            return false;
        }
    if(fm_company == "Required" && (!CheckField(frm, "form[company]", msg_company_name))) return false;
	if(!CheckField(frm, "form[address1]", msg_address_line1)) return false;
	if(fm_address2 == "Required" && (!CheckField(frm, "form[address2]", msg_address_line2))) return false;
	if(!CheckField(frm, "form[city]", msg_city_name)) return false;
	
	if(!CheckField(frm, "form[country]", msg_country)) return false;
	if(frm.elements["form[state]"].options.length > 1){
		if(frm.elements["form[state]"].value == "" || frm.elements["form[state]"].value == "0"){
			alert(msg_select_province_state);
			frm.elements["form[state]"].focus();
			return false;
		}
	}
	else{
		if(!CheckField(frm, "form[province]", msg_custom_province_state)) return false;
	}
	
	if(!CheckField(frm, "form[zip]", msg_zip_postal_code)) return false;
	if(fm_phone == "Required" && (!CheckField(frm, "form[phone]", msg_phone_number))) return false;
    if(!isPhoneNumber(frm.elements["form[phone]"].value))
    {   frm.elements["form[phone]"].focus(); return false;
    } 
        /*if(!rex.test(frm.elements["form[phone]"].value)){
            alert('Please enter valid phone number.\nIt must be a numeric value.');
            frm.elements["form[phone]"].focus();
            return false;
        } */
	if(!CheckCustomFields(frm, 'billing')){
		return false;	
	}
	
	if(!ship2all && frm.elements["form[thesame]"].checked){
		//check shipping country
		c = frm.elements["form[country]"].value;
		is_country = false;
		for(i=1; i<= ship2countries.length; i++){
			if(ship2countries[i] == c){
				is_country = true;
			}
		}
		if(!is_country){
			alert(msg_incorrect_shipping_address);
			return false;
		}
	}
	
	if(!CheckField(frm, "form[email]", msg_email_address)) return false;
	if(!isEmail(frm.elements["form[email]"].value)){
		alert(msg_enter_valid_email);
		frm.elements["form[email]"].focus();
		return false;
	}
	if(!CheckField(frm, "form[login]", msg_username)) return false;
	if(!CheckField(frm, "form[password]", msg_password)) return false;
	if(!CheckField(frm, "form[password2]", msg_password_confirmation)) return false;
	
	if(!CheckCustomFields(frm, 'account')){
		return false;	
	}
	
	if(!CheckCustomFields(frm, 'signup')){
		return false;	
	}
	
	if(frm.elements["form[agree]"]){
		if(frm.elements["form[agree]"].checked == false){
			alert(msg_read_terms_before_registration);
			return false;
		}
	}
	return true;
}

function CheckShippingAddress(frm, fm_company, fm_address2){
	if(!CheckField(frm, "form[name]", msg_name)) return false;
	if(fm_company == "Required" && (!CheckField(frm, "form[company]", msg_company_name))) return false;
	if(!CheckField(frm, "form[address1]", msg_address_line1)) return false;
	if(fm_address2 == "Required" && (!CheckField(frm, "form[address2]", msg_address_line2))) return false;
	if(!CheckField(frm, "form[city]", msg_city_name)) return false;
	
	
	//check is state/province select OR custom state/province
	sd = document.getElementById('div_shipping_address_state');

	if(sd.style.display == "block"){
		//check province/state from select
		if(frm.elements["form[state]"].value == "" || frm.elements["form[state]"].value == "0"){
			alert(msg_select_province_state);
			frm.elements["form[state]"].focus();
			return false;
		}
	}
	else{
		//check custom province/state
		if(!CheckField(frm, "form[province]", msg_custom_province_state)) return false;
	}
	
	if(!CheckField(frm, "form[zip]", msg_zip_postal_code)) return false;
	
	if(!CheckCustomFields(frm, 'shipping')){
		return false;	
	}
	
	return true;
}

///////////////////////////////
// CHECK PROFILE FORM
function CheckProfileForm(frm, fm_company, fm_address2, fm_phone){
	if(!CheckField(frm, "form[fname]", msg_first_name)) return false;
    var rexfirst = /^[a-zA-Z \-\' ]*$/
    if(!rexfirst.test(frm.elements["form[fname]"].value)){
            alert('Please enter valid first name');
            frm.elements["form[fname]"].focus();
            return false;
        }
    if(!CheckField(frm, "form[lname]", msg_last_name)) return false;
    if(!rexfirst.test(frm.elements["form[lname]"].value)){
            alert('Please enter valid last name');
            frm.elements["form[lname]"].focus();
            return false;
        }
	if(!CheckField(frm, "form[lname]", msg_last_name)) return false;
	if(fm_company == "Required" && (!CheckField(frm, "form[company]", msg_company_name))) return false;
	if(!CheckField(frm, "form[address1]", msg_address_line1)) return false;
	if(fm_address2 == "Required" && (!CheckField(frm, "form[address2]", msg_address_line2))) return false;
	if(!CheckField(frm, "form[city]", msg_city_name)) return false;
	if(!CheckField(frm, "form[country]", msg_country)) return false;
	if(!CheckField(frm, "form[country]", msg_country)) return false;
	if(frm.elements["form[state]"].options.length > 1){
		if(frm.elements["form[state]"].value == "" || frm.elements["form[state]"].value == "0"){
			alert(msg_select_province_state);
			frm.elements["form[state]"].focus();
			return false;
		}
	}
	else{
		if(!CheckField(frm, "form[province]", msg_custom_province_state)) return false;
	}
	
	if(!CheckField(frm, "form[zip]", msg_zip_postal_code)) return false;
	if(fm_phone == "Required" && (!CheckField(frm, "form[phone]", msg_phone_number))) return false;
    if(!isPhoneNumber(frm.elements["form[phone]"].value))
    {   frm.elements["form[phone]"].focus(); return false;
    } 
    
	if(!CheckField(frm, "form[email]", msg_email_address)) return false;
	if(!isEmail(frm.elements["form[email]"].value)){
		alert(msg_enter_valid_email);
		frm.elements["form[email]"].focus();
		return false;
	}
	
	if(!CheckCustomFields(frm, 'billing')){
		return false;	
	}
	
	if(frm.elements["form[password]"].value != ""){
		if(frm.elements["form[password]"].value != frm.elements["form[password2]"].value){
			alert(msg_different_password_and_comfirmation);
			frm.elements["form[password]"].focus();
			return false;
		}
	}
	
	if(!CheckCustomFields(frm, 'account')){
		return false;	
	}
	
	return true;
}

function CheckEmail2FriendForm(frm){ 
	if(!CheckField(frm, "yname", msg_your_name)) return false;
  /*  var rexfirst = /^[a-zA-Z \-\' ]*$/
    if(!rexfirst.test(frm.elements["yname"].value))
    {
            alert('Please enter valid your name');
            frm.elements["yname"].focus();
            return false;
    }  */
	if(!CheckField(frm, "yemail", msg_your_email_address)) return false;
	if(!isEmail(frm.elements["yemail"].value)){
		alert(msg_enter_valid_email);
		frm.elements["yemail"].focus();
		return false;
	}
	if(!CheckField(frm, "fname", msg_your_friend_name)) return false;
	/*if(!rexfirst.test(frm.elements["fname"].value))
    {
            alert('Please enter valid your friend\'s name');
            frm.elements["fname"].focus();
            return false;
    } */
    if(!CheckField(frm, "femail", msg_your_friend_email_address)) return false;
	if(!isEmail(frm.elements["femail"].value)){
		alert(msg_enter_valid_email);
		frm.elements["femail"].focus();
		return false;
	}
    
    if(!CheckField(frm, "comments", "comment")) return false;   
    
	return true;
}

function ConfirmDeleteShippingAddress(address_id){
	if(confirm(msg_confirm_delete_shipping_address)){
		document.location = site_dinamic_url + 'ua=' + USER_DELETE_ADDRESS + '&address_id=' + address_id;
	}
}

function CheckWishlistName(frm){
	if(!CheckField(frm, "wishlist_name", msg_enterWishlistName)) return false;	
	return true;
}
function CheckWishlistEmailFrm(frm){
	if(!CheckField(frm, "mail_subject", "subject")) return false;	
	if(!isEmail(frm.elements["your_email"].value)){
		alert(msg_enter_valid_email);
		frm.elements["your_email"].focus();
		return false;
	}
	return true;
}
function ConfirmDeleteWishlist(wl_id){
	if(confirm(msg_confirm_delete_wishlist)){		
		document.location = site_dinamic_url + 'p=manage_wishlist&wl_action=delete_wishlist&wlid=' + wl_id;
	}
}

function ConfirmDeleteWishlistProduct(wlp_id){
	if(confirm(msg_confirm_delete_wishlist_product)){		
		document.location = site_dinamic_url + 'p=manage_wishlist&wl_action=delete_product&wlpid=' + wlp_id;
	}
}

function detectSearchEnter(e,funname)
{   
  var keynum;
  var returnVal;
  if(window.event) // IE
  {
     keynum = e.keyCode;
  }
  else if(e.which) // Netscape/Firefox/Opera
  {
     keynum = e.which;
  }

  if(keynum == 13)
  {  
    returnVal = funname(); 
  }
  
  return returnVal;
}

function CheckSKUAddProduct(frm, min_order, max_order, allowed_max){ 
    globalfrm = frm;
   var target = document.getElementById('searchStr');
   target.value = target.value.trim(); 
   if(target.value == '')
   {
       alert('Please enter Product ID');
       target.focus();
       return false;
   }
   var oa_id_display = document.getElementById('oa_id_display');
   oa_id_display.value = oa_id_display.value.trim();
   if(oa_id_display.value == '')
   {
       alert('Please select Product ID');
       oa_id_display.focus();
       return false;
   }
   /*else if(globalflag == "false")
   {
        alert('Please enter correct Product ID');
        target.focus();
        return false;
   } */
    var allowed_max = document.getElementById('oa_id');
    var alow = allowed_max.value;
    var arr = alow.split("#@#");
    if((arr[4] !='') && (arr[4] != undefined)) 
        allowed_max = arr[4];
    else    
        allowed_max = arr[1];
    var user_type = document.getElementById('user_type').value; 
        if(user_type=='Special')
        {
             var allowed_max = '-'; 
        } 
    if(product_may_be_added){
        var rex = /^(\d{1,})$/
        if(!rex.test(frm.elements["oa_quantity"].value)){
            alert(msg_enter_numeric_product_quantity);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((frm.elements["oa_quantity"].value *1) < min_order){
            alert(msg_number_of_items_exceeded_min);
            frm.elements["oa_quantity"].focus();
            return false;
        }
         if(allowed_max == 0){
            displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Very sorry.  We don\'t have that many items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type=button value="Yes" onclick=\'closeMessage();quick_order_attribute_verify(true)\'><input type=button value="No" onclick=\'closeMessage();verify(false)\'></p>',false);return false 
            //alert('Very sorry. Product is out of stock');
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((max_order != "-") && (frm.elements["oa_quantity"].value * 1 > max_order)){
            alert(msg_number_of_items_exceeded_max);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((allowed_max != "-") && (frm.elements["oa_quantity"].value * 1 > allowed_max)){
            //alert('Very sorry.  We only have '+ allowed_max +' items in stock.');
           // alert(msg_number_of_items_exceed_inventory);
            displayStaticMessage_forall("<p><font style='font-size:12px;font-weight:bold;' color='#FFFFFF'>Very sorry.  We only have "+ allowed_max +" items in stock.<br/>Would you like to request more ?</font></p><br/><p><input type='button' value='Yes' onclick=\'closeMessage();quick_order_attribute_verify(true)\'><input type='button' value='No' onclick=\'closeMessage();verify(false)\'></p>",false);return false 
            frm.elements["oa_quantity"].focus();
            return false;
        }
        return true;
    }
    return false;
}
function CheckBestsellerAddProduct(frm, min_order, max_order, allowed_max){
    var product_may_be_added = true;
    if(product_may_be_added){ 
        var rex = /^(\d{1,})$/
        if(!rex.test(frm.elements["oa_quantity"].value)){
            alert(msg_enter_numeric_product_quantity);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((frm.elements["oa_quantity"].value *1) < min_order){
            alert(msg_number_of_items_exceeded_min);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((max_order != "-") && (frm.elements["oa_quantity"].value * 1 > max_order)){
            alert(msg_number_of_items_exceeded_max);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        if((allowed_max != "-") && (frm.elements["oa_quantity"].value * 1 > allowed_max)){
            alert('Very sorry.  We only have '+ allowed_max +' items in stock.');
           // alert(msg_number_of_items_exceed_inventory);
            frm.elements["oa_quantity"].focus();
            return false;
        }
        return true;
    }
    return false;
} 
/*-- Added by dinesh for validating the product request form
Date : 27/05/2010 */
function Checkproductrequestform(frm){
    
    var currentTime = new Date();
    var month = currentTime.getMonth();
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var cur_date = day+"/"+month+"/"+year;
    if(document.getElementById('product_stock') != null)
    {
        var product_stock = parseInt(document.getElementById('product_stock').innerHTML);
        var product_sku = document.getElementById('form[productsku]').value;
    }
    
    if(!CheckField(frm, "form[first_name]", msg_first_name)) return false;
    var rexfirst = /^[a-zA-Z \-\' ]*$/
    if(!rexfirst.test(frm.elements["form[first_name]"].value)){
        alert('Please enter valid first name');
        frm.elements["form[first_name]"].focus();
        return false;
    }
        
   if(!CheckField(frm, "form[last_name]", msg_last_name)) return false;
    var rexfirst = /^[a-zA-Z \-\' ]*$/
    if(!rexfirst.test(frm.elements["form[last_name]"].value)){
        alert('Please enter valid last name');
        frm.elements["form[last_name]"].focus();
        return false;
    }     
    
    if(!CheckField(frm, "form[email]", "email")) return false;
    if(!isEmail(frm.elements["form[email]"].value)){
        alert(msg_enter_valid_email);
        frm.elements["form[email]"].focus();
        return false;
    }  
    if(!CheckField(frm, "form[phone_number]", "phone number")) return false;
    if(!isPhoneNumber(frm.elements["form[phone_number]"].value))
    {   frm.elements["form[phone_number]"].focus(); return false;
    } 
    if(!CheckField(frm, "form[qty]", "quantity")) return false;
    var rex = /^(\d{1,})$/
        if(!rex.test(frm.elements["form[qty]"].value)){
            alert(msg_enter_numeric_product_quantity);
            frm.elements["form[qty]"].focus();
            return false;
        }
    if((document.getElementById('product_stock') != null) && (frm.elements["form[qty]"].value <= product_stock))
    {
        displayStaticMessage_forall('<p><font style="font-size:12px;font-weight:bold;" color="#FFFFFF">Good news.  We currently have '+frm.elements["form[qty]"].value+' of '+product_sku+' in stock now.<br/>Just close this request window to place an order.</font></p><br/><p><input type=button value="Ok" onclick=\'closeMessage();verify(false)\'></p>',false);
        return false;
    }    
    if(!CheckField(frm, "currdate", "date")) return false;
    var selectdate = document.getElementById("currdate");
    var selectarr = selectdate.value.split("/");
    var selecteddate =  selectarr[1]+"/"+(selectarr[0]-1)+"/"+selectarr[2];
    var dt1=getCompareDate(selecteddate,"/");
    var dt2=getCompareDate(cur_date,"/");
    if(dt2 > dt1)
    {
         alert("Please enter a current date or future date"); 
         return false;
    }
    var div_progress = document.getElementById("productrequestloading");
    var requestFRM = document.getElementById("requestFRM");
    if(div_progress)
    {
          requestFRM.style.display = "none";
          emailwindow.setSize(350, 200);
          div_progress.style.display = "block";
    }  
    xajax_processAjaxAction("productrequest", xajax.getFormValues(frm)); 
    return false;
}

/*-- Added by dinesh for validating the tracking form
Date : 06/07/2010 */
function checkordertrackingform(frm)
{ 
    if(!CheckField(frm, "order_number", "order number")) return false;
    if(!CheckField(frm, "postal_code", "shipping zip/postal code")) return false; 
    return true;        
}

function isPhoneNumber(phonenumber)
{
 var numaric = phonenumber; 
 if(numaric.length < 8)
 {
     alert("Please enter valid phone number");
     return false; 
 }
 /*for(var j=0; j<numaric.length; j++)
  {
    var alphaa = numaric.charAt(j);
    var hh = alphaa.charCodeAt(0);
    // Added by dinesh for checking the phone number field with numbers from 0 to 9
    // ascii value of 45 is - and 32 is space
    if((hh > 47 && hh<58) || (hh == 45) || (hh == 32))
    {
    }
  else {
           alert("Please enter valid phone number.\nIt must be a numeric value.");
    return false;
    }
   } */
   return true;
}
function verify(ver)
{
        if(ver)
        {
             emailwindow=dhtmlmodal.open('EmailBox', 'div', 'productrequest', 'Product Request Form', 'width=450px,height=400px,center=1,resize=1,scrolling=0');
        }
}
function displayMessage(url)
{
    
    messageObj.setSource(url);
    messageObj.setCssClassMessageBox(false);
    messageObj.setSize(400,200);
    messageObj.setShadowDivVisible(true);    // Enable shadow for these boxes
    messageObj.display();
}

function displayStaticMessage_forall(messageContent,cssClass)
{
    messageObj.setHtmlContent(messageContent);
    messageObj.setSize(380,100);
    messageObj.setCssClassMessageBox(cssClass);
    messageObj.setSource(false);    // no html source since we want to use a static message here.
    messageObj.setShadowDivVisible(false);    // Disable shadow for these boxes    
    messageObj.display();
    
    
}

function closeMessage()
{
    messageObj.close();    
}
function displayItemAddedAlert(messageContent,cssClass)
{
    var messageText = messageContent + '<br><br><div style="align:right"><input type="button" value="OK" onclick="javascript:closeMessage();">';
     
    messageObj.setHtmlContent(messageText);
    messageObj.setSize(300,70);
    messageObj.setCssClassMessageBox(cssClass);
    messageObj.setSource(false);    // no html source since we want to use a static message here.
    messageObj.setShadowDivVisible(false);    // Disable shadow for these boxes    
    messageObj.display(); 
    
    setTimeout(closeMessage, 2000)
}

function showItemAddedToCartPopUp()
{
    var productname = document.getElementById('qty_added').value; 
    displayItemAddedAlert(productname + ' Item(s) Added To Cart',false)
}

function getCompareDate(dateString,dateSeperator)
{
    //This function return a date object after accepting 
    //a date string ans dateseparator as arguments
    var curValue=dateString;
    var sepChar=dateSeperator;
    var curPos=0;
    var cDate,cMonth,cYear;
    //extract day portion
    curPos=dateString.indexOf(sepChar);
    cDate=dateString.substring(0,curPos);
    
    //extract month portion                
    endPos=dateString.indexOf(sepChar,curPos+1);            cMonth=dateString.substring(curPos+1,endPos); 

    //extract year portion                
    curPos=endPos;
    endPos=curPos+5;            
    cYear=curValue.substring(curPos+1,endPos);
    //Create Date Object
    dtObject=new Date(cYear,cMonth,cDate);    
    return dtObject;
}

function loadAutoCompleteFrame(){
    var inp = document.getElementById('searchStr');
    var lim = document.getElementById('searchLimit');
    var fra = document.getElementById('acFrame');
    inp.className = "ui-autocomplete-loading";
    if(document.all){
        document.frames['acFrame'].document.location='index.php?p=auto_complete&mode=order_by_sku&chart=true&q=' + escape(inp.value) + '&l=' + lim.value;
    }
    else{
        fra.setAttribute("src", 'index.php?p=auto_complete&mode=order_by_sku&chart=true&q=' + escape(inp.value) + '&l=' + lim.value);
    }
}

function hideACDiv(){
    var d = document.getElementById('acDiv');
    if(d){
        d.style.visibility = 'hidden';
    }
}
function onQuickLink(item){
    item.className = item.active=="yes"?"quickLinkActiveOn":"quickLinkOn";
    window.status = "Front Area: " + item.statustext;
}
function offQuickLink(item){
    item.className = item.active=="yes"?"quickLinkActiveOff":"quickLinkOff";
    window.status = "Front Area";
}
function gotoQuickLinkItem(url){
    document.location = url;
}

function Select_Product(pid,product_id){
    var h = document.getElementById('pid_' + pid+'_'+product_id);
    var selectpid = document.getElementById('selectpid_' + pid+'_'+product_id);
    var s = document.getElementById('oa_id');
    var oa_id_display = document.getElementById('oa_id_display');
    var oa_id_display_value = document.getElementById('oa_id_display_value');
    var searchStr = document.getElementById('searchStr'); 
    if(h && s){
        exists = false;
        for(i=0; i < s.length; i++){
            if(s.value == pid){
                exists = true;
                break;
            }
        }
        if(exists){
            alert("This products already added");
            return false;
        }
        else{
            var p_value = h.value;
            s.value = p_value.replace(/ - /gi, "#@#");
            searchStr.value = selectpid.value;
            oa_id_display.value = selectpid.value;
            oa_id_display_value.innerHTML = selectpid.value;
            hideACDiv();
        }
    }
}

/* dhtmlwindow.js */

// -------------------------------------------------------------------
// DHTML Window Widget- By Dynamic Drive, available at: http://www.dynamicdrive.com
// v1.0: Script created Feb 15th, 07'
// v1.01: Feb 21th, 07' (see changelog.txt)
// v1.02: March 26th, 07' (see changelog.txt)
// v1.03: May 5th, 07' (see changelog.txt)
// v1.1:  Oct 29th, 07' (see changelog.txt)
// -------------------------------------------------------------------

var dhtmlwindow={
imagefiles:['images/images/english/min.gif', 'images/images/english/close.gif', 'images/images/english/restore.gif', 'images/images/english/resize.gif'], //Path to 4 images used by script, in that order
ajaxbustcache: true, //Bust caching when fetching a file via Ajax?
ajaxloadinghtml: '<b>Loading Page. Please wait...</b>', //HTML to show while window fetches Ajax Content?

minimizeorder: 0,
zIndexvalue:100,
tobjects: [], //object to contain references to dhtml window divs, for cleanup purposes
lastactivet: {}, //reference to last active DHTML window

init:function(t){
    var domwindow=document.createElement("div") //create dhtml window div
    domwindow.id=t
    domwindow.className="dhtmlwindow"
    var domwindowdata=''
    domwindowdata='<div class="drag-handle">'
    domwindowdata+='<div id="lightwindow_title_bar">'+'<div class="drag-controls" id="lightwindow_title_bar_inner"  style="height: 25px; margin-top: 0px;">'+                        '<span id="lightwindow_title_bar_title"></span>'+
                        '<a id="lightwindow_title_bar_close_link" >Close</a>'+
                        '</div>'+'</div>'
    domwindowdata+='</div>'
    domwindowdata+='<div class="drag-contentarea">'
    domwindowdata+='<div class="drag-statusarea"><div class="drag-resizearea"></div></div>'
    domwindowdata+='</div>'
    domwindow.innerHTML=domwindowdata
    document.getElementById("dhtmlwindowholder").appendChild(domwindow)
    //this.zIndexvalue=(this.zIndexvalue)? this.zIndexvalue+1 : 100 //z-index value for DHTML window: starts at 0, increments whenever a window has focus
    var t=document.getElementById(t)
    var divs=t.getElementsByTagName("div")
    for (var i=0; i<divs.length; i++){ //go through divs inside dhtml window and extract all those with class="drag-" prefix
        if (/drag-/.test(divs[i].className))
            t[divs[i].className.replace(/drag-/, "")]=divs[i] //take out the "drag-" prefix for shorter access by name
    }
    //t.style.zIndex=this.zIndexvalue //set z-index of this dhtml window
    t.handle._parent=t //store back reference to dhtml window
    t.resizearea._parent=t //same
    t.controls._parent=t //same
    t.onclose=function(){return true} //custom event handler "onclose"
    t.onmousedown=function(){dhtmlwindow.setfocus(this)} //Increase z-index of window when focus is on it
    t.handle.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on handle div
    t.resizearea.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on resize div
    t.controls.onclick=dhtmlwindow.enablecontrols
    t.show=function(){dhtmlwindow.show(this)} //public function for showing dhtml window
    t.hide=function(){dhtmlwindow.hide(this)} //public function for hiding dhtml window
    t.close=function(){dhtmlwindow.close(this)} //public function for closing dhtml window (also empties DHTML window content)
    t.setSize=function(w, h){dhtmlwindow.setSize(this, w, h)} //public function for setting window dimensions
    t.moveTo=function(x, y){dhtmlwindow.moveTo(this, x, y)} //public function for moving dhtml window (relative to viewpoint)
    t.isResize=function(bol){dhtmlwindow.isResize(this, bol)} //public function for specifying if window is resizable
    t.isScrolling=function(bol){dhtmlwindow.isScrolling(this, bol)} //public function for specifying if window content contains scrollbars
    t.load=function(contenttype, contentsource, title){dhtmlwindow.load(this, contenttype, contentsource, title)} //public function for loading content into window
    this.tobjects[this.tobjects.length]=t
    return t //return reference to dhtml window div
},

open:function(t, contenttype, contentsource, title, attr, recalonload){
    var d=dhtmlwindow //reference dhtml window object
    function getValue(Name){
        var config=new RegExp(Name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
        return (config.test(attr))? parseInt(RegExp.$1) : 0 //return value portion (int), or 0 (false) if none found
    }
    if (document.getElementById(t)==null) //if window doesn't exist yet, create it
        t=this.init(t) //return reference to dhtml window div
    else
        t=document.getElementById(t)
    this.setfocus(t)
    t.setSize(getValue(("width")), (getValue("height"))) //Set dimensions of window
    var xpos=getValue("center")? "middle" : getValue("left") //Get x coord of window
    var ypos=getValue("center")? "middle" : getValue("top") //Get y coord of window
    //t.moveTo(xpos, ypos) //Position window
    if (typeof recalonload!="undefined" && recalonload=="recal" && this.scroll_top==0){ //reposition window when page fully loads with updated window viewpoints?
        if (window.attachEvent && !window.opera) //In IE, add another 400 milisecs on page load (viewpoint properties may return 0 b4 then)
            this.addEvent(window, function(){setTimeout(function(){t.moveTo(xpos, ypos)}, 400)}, "load")
        else
            this.addEvent(window, function(){t.moveTo(xpos, ypos)}, "load")
    }
    t.isResize(getValue("resize")) //Set whether window is resizable
    t.isScrolling(getValue("scrolling")) //Set whether window should contain scrollbars
    t.style.visibility="visible"
    t.style.display="block"
    t.contentarea.style.display="block"
    t.moveTo(xpos, ypos) //Position window
    t.load(contenttype, contentsource, title)
    if (t.state=="minimized" && t.controls.firstChild.title=="Restore"){ //If window exists and is currently minimized?
        t.controls.firstChild.setAttribute("src", dhtmlwindow.imagefiles[0]) //Change "restore" icon within window interface to "minimize" icon
        t.controls.firstChild.setAttribute("title", "Minimize")
        t.state="fullview" //indicate the state of the window as being "fullview"
    }
    return t
},

setSize:function(t, w, h){ //set window size (min is 150px wide by 100px tall)
    t.style.width=Math.max(parseInt(w), 150)+"px"
    t.contentarea.style.height=Math.max(parseInt(h), 100)+"px"
},

moveTo:function(t, x, y){ //move window. Position includes current viewpoint of document
    this.getviewpoint() //Get current viewpoint numbers
    t.style.left=(x=="middle")? this.scroll_left+(this.docwidth-t.offsetWidth)/2+"px" : this.scroll_left+parseInt(x)+"px"
    t.style.top=(y=="middle")? this.scroll_top+(this.docheight-t.offsetHeight)/2+"px" : this.scroll_top+parseInt(y)+"px"
},

isResize:function(t, bol){ //show or hide resize inteface (part of the status bar)
    t.statusarea.style.display=(bol)? "block" : "none"
    t.resizeBool=(bol)? 1 : 0
},

isScrolling:function(t, bol){ //set whether loaded content contains scrollbars
    t.contentarea.style.overflow=(bol)? "auto" : "hidden"
},

load:function(t, contenttype, contentsource, title){ //loads content into window plus set its title (3 content types: "inline", "iframe", or "ajax")
    if (t.isClosed){
        alert("DHTML Window has been closed, so no window to load contents into. Open/Create the window again.")
        return
    }
    var contenttype=contenttype.toLowerCase() //convert string to lower case
    if (typeof title!="undefined")
        t.handle.firstChild.nodeValue=title
    if (contenttype=="inline")
        t.contentarea.innerHTML=contentsource
    else if (contenttype=="div"){
        var inlinedivref=document.getElementById(contentsource)
        t.contentarea.innerHTML=(inlinedivref.defaultHTML || inlinedivref.innerHTML) //Populate window with contents of inline div on page
        if (!inlinedivref.defaultHTML)
            inlinedivref.defaultHTML=inlinedivref.innerHTML //save HTML within inline DIV
        inlinedivref.innerHTML="" //then, remove HTML within inline DIV (to prevent duplicate IDs, NAME attributes etc in contents of DHTML window
        inlinedivref.style.display="none" //hide that div
    }
    else if (contenttype=="iframe"){
        t.contentarea.style.overflow="hidden" //disable window scrollbars, as iframe already contains scrollbars
        if (!t.contentarea.firstChild || t.contentarea.firstChild.tagName!="IFRAME") //If iframe tag doesn't exist already, create it first
            t.contentarea.innerHTML='<iframe src="" style="margin:0; padding:0; width:100%; height: 100%" name="_iframe-'+t.id+'"></iframe>'
        window.frames["_iframe-"+t.id].location.replace(contentsource) //set location of iframe window to specified URL
        }
    else if (contenttype=="ajax"){
        this.ajax_connect(contentsource, t) //populate window with external contents fetched via Ajax
    }
    t.contentarea.datatype=contenttype //store contenttype of current window for future reference
},

setupdrag:function(e){
    var d=dhtmlwindow //reference dhtml window object
    var t=this._parent //reference dhtml window div
    d.etarget=this //remember div mouse is currently held down on ("handle" or "resize" div)
    var e=window.event || e
    d.initmousex=e.clientX //store x position of mouse onmousedown
    d.initmousey=e.clientY
    d.initx=parseInt(t.offsetLeft) //store offset x of window div onmousedown
    d.inity=parseInt(t.offsetTop)
    d.width=parseInt(t.offsetWidth) //store width of window div
    d.contentheight=parseInt(t.contentarea.offsetHeight) //store height of window div's content div
    if (t.contentarea.datatype=="iframe"){ //if content of this window div is "iframe"
        t.style.backgroundColor="#F8F8F8" //colorize and hide content div (while window is being dragged)
        t.contentarea.style.visibility="hidden"
    }
    document.onmousemove=d.getdistance //get distance travelled by mouse as it moves
    document.onmouseup=function(){
        if (t.contentarea.datatype=="iframe"){ //restore color and visibility of content div onmouseup
            t.contentarea.style.backgroundColor="white"
            t.contentarea.style.visibility="visible"
        }
        d.stop()
    }
    return false
},

getdistance:function(e){
    var d=dhtmlwindow
    var etarget=d.etarget
    var e=window.event || e
    d.distancex=e.clientX-d.initmousex //horizontal distance travelled relative to starting point
    d.distancey=e.clientY-d.initmousey
    if (etarget.className=="drag-handle") //if target element is "handle" div
        d.move(etarget._parent, e)
    else if (etarget.className=="drag-resizearea") //if target element is "resize" div
        d.resize(etarget._parent, e)
    return false //cancel default dragging behavior
},

getviewpoint:function(){ //get window viewpoint numbers
    var ie=document.all && !window.opera
    var domclientWidth=document.documentElement && parseInt(document.documentElement.clientWidth) || 100000 //Preliminary doc width in non IE browsers
    this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
    this.scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
    this.scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
    this.docwidth=(ie)? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(domclientWidth, window.innerWidth-16)
    this.docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
},

rememberattrs:function(t){ //remember certain attributes of the window when it's minimized or closed, such as dimensions, position on page
    this.getviewpoint() //Get current window viewpoint numbers
    t.lastx=parseInt((t.style.left || t.offsetLeft))-dhtmlwindow.scroll_left //store last known x coord of window just before minimizing
    t.lasty=parseInt((t.style.top || t.offsetTop))-dhtmlwindow.scroll_top
    t.lastwidth=parseInt(t.style.width) //store last known width of window just before minimizing/ closing
},

move:function(t, e){
    t.style.left=dhtmlwindow.distancex+dhtmlwindow.initx+"px"
    t.style.top=dhtmlwindow.distancey+dhtmlwindow.inity+"px"
},

resize:function(t, e){
    t.style.width=Math.max(dhtmlwindow.width+dhtmlwindow.distancex, 150)+"px"
    t.contentarea.style.height=Math.max(dhtmlwindow.contentheight+dhtmlwindow.distancey, 100)+"px"
},

enablecontrols:function(e){
    var d=dhtmlwindow
    var sourceobj=window.event? window.event.srcElement : e.target //Get element within "handle" div mouse is currently on (the controls)
    if (/Minimize/i.test(sourceobj.getAttribute("title"))) //if this is the "minimize" control
        d.minimize(sourceobj, this._parent)
    else if (/Restore/i.test(sourceobj.getAttribute("title"))) //if this is the "restore" control
        d.restore(sourceobj, this._parent)
    else if (/Close/i.test(sourceobj.getAttribute("title"))) //if this is the "close" control
        d.close(this._parent)
    return false
},

minimize:function(button, t){
    dhtmlwindow.rememberattrs(t)
    button.setAttribute("src", dhtmlwindow.imagefiles[2])
    button.setAttribute("title", "Restore")
    t.state="minimized" //indicate the state of the window as being "minimized"
    t.contentarea.style.display="none"
    t.statusarea.style.display="none"
    if (typeof t.minimizeorder=="undefined"){ //stack order of minmized window on screen relative to any other minimized windows
        dhtmlwindow.minimizeorder++ //increment order
        t.minimizeorder=dhtmlwindow.minimizeorder
    }
    t.style.left="10px" //left coord of minmized window
    t.style.width="200px"
    var windowspacing=t.minimizeorder*10 //spacing (gap) between each minmized window(s)
    t.style.top=dhtmlwindow.scroll_top+dhtmlwindow.docheight-(t.handle.offsetHeight*t.minimizeorder)-windowspacing+"px"
},

restore:function(button, t){
    dhtmlwindow.getviewpoint()
    button.setAttribute("src", dhtmlwindow.imagefiles[0])
    button.setAttribute("title", "Minimize")
    t.state="fullview" //indicate the state of the window as being "fullview"
    t.style.display="block"
    t.contentarea.style.display="block"
    if (t.resizeBool) //if this window is resizable, enable the resize icon
        t.statusarea.style.display="block"
    t.style.left=parseInt(t.lastx)+dhtmlwindow.scroll_left+"px" //position window to last known x coord just before minimizing
    t.style.top=parseInt(t.lasty)+dhtmlwindow.scroll_top+"px"
    t.style.width=parseInt(t.lastwidth)+"px"
},


close:function(t){
   // updateDateField("currdate");
    try{
        var closewinbol=t.onclose()
    }
    catch(err){ //In non IE browsers, all errors are caught, so just run the below
        var closewinbol=true
 }
    finally{ //In IE, not all errors are caught, so check if variable isn't defined in IE in those cases
        if (typeof closewinbol=="undefined"){
            alert("An error has occured somwhere inside your \"onclose\" event handler")
            var closewinbol=false
        }
    }
    if (closewinbol){ //if custom event handler function returns true
        if (t.state!="minimized") //if this window isn't currently minimized
            dhtmlwindow.rememberattrs(t) //remember window's dimensions/position on the page before closing
        if (window.frames["_iframe-"+t.id]) //if this is an IFRAME DHTML window
            window.frames["_iframe-"+t.id].location.replace("about:blank")
        else
            t.contentarea.innerHTML=""
        t.style.display="none"
        t.isClosed=true //tell script this window is closed (for detection in t.show())
    }
    return closewinbol
},


setopacity:function(targetobject, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
    if (!targetobject)
        return
    if (targetobject.filters && targetobject.filters[0]){ //IE syntax
        if (typeof targetobject.filters[0].opacity=="number") //IE6
            targetobject.filters[0].opacity=value*100
        else //IE 5.5
            targetobject.style.filter="alpha(opacity="+value*100+")"
        }
    else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
        targetobject.style.MozOpacity=value
    else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
        targetobject.style.opacity=value
},

setfocus:function(t){ //Sets focus to the currently active window
    this.zIndexvalue++
    t.style.zIndex=this.zIndexvalue
    t.isClosed=false //tell script this window isn't closed (for detection in t.show())
    this.setopacity(this.lastactivet.handle, 0.5) //unfocus last active window
    this.setopacity(t.handle, 1) //focus currently active window
    this.lastactivet=t //remember last active window
},


show:function(t){
    if (t.isClosed){
        alert("DHTML Window has been closed, so nothing to show. Open/Create the window again.")
        return
    }
    if (t.lastx) //If there exists previously stored information such as last x position on window attributes (meaning it's been minimized or closed)
        dhtmlwindow.restore(t.controls.firstChild, t) //restore the window using that info
    else
        t.style.display="block"
    this.setfocus(t)
    t.state="fullview" //indicate the state of the window as being "fullview"
},

hide:function(t){
    t.style.display="none"
},

ajax_connect:function(url, t){
    var page_request = false
    var bustcacheparameter=""
    if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
        page_request = new XMLHttpRequest()
    else if (window.ActiveXObject){ // if IE6 or below
        try {
        page_request = new ActiveXObject("Msxml2.XMLHTTP")
        } 
        catch (e){
            try{
            page_request = new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch (e){}
        }
    }
    else
        return false
    t.contentarea.innerHTML=this.ajaxloadinghtml
    page_request.onreadystatechange=function(){dhtmlwindow.ajax_loadpage(page_request, t)}
    if (this.ajaxbustcache) //if bust caching of external page
        bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
    page_request.open('GET', url+bustcacheparameter, true)
    page_request.send(null)
},

ajax_loadpage:function(page_request, t){
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
    t.contentarea.innerHTML=page_request.responseText
    }
},


stop:function(){
    dhtmlwindow.etarget=null //clean up
    document.onmousemove=null
    document.onmouseup=null
},

addEvent:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
    var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
    if (target.addEventListener)
        target.addEventListener(tasktype, functionref, false)
    else if (target.attachEvent)
        target.attachEvent(tasktype, functionref)
},

cleanup:function(){
    for (var i=0; i<dhtmlwindow.tobjects.length; i++){
        dhtmlwindow.tobjects[i].handle._parent=dhtmlwindow.tobjects[i].resizearea._parent=dhtmlwindow.tobjects[i].controls._parent=null
    }
    window.onload=null
}

} //End dhtmlwindow object

document.write('<div id="dhtmlwindowholder"><span style="display:none">.</span></div>') //container that holds all dhtml window divs on page
window.onunload=dhtmlwindow.cleanup
 /* End */

/* modal.js */

// -------------------------------------------------------------------
// DHTML Modal window- By Dynamic Drive, available at: http://www.dynamicdrive.com
// v1.0: Script created Feb 27th, 07'
// v1.01 May 5th, 07' Minor change to modal window positioning behavior (not a bug fix)
// v1.1: April 16th, 08' Brings it in sync with DHTML Window widget. See changelog.txt for the later for changes.
// REQUIRES: DHTML Window Widget (v1.01 or higher): http://www.dynamicdrive.com/dynamicindex8/dhtmlwindow/
// -------------------------------------------------------------------

if (typeof dhtmlwindow=="undefined")
alert('ERROR: Modal Window script requires all files from "DHTML Window widget" in order to work!')
var dhtmlmodal={
veilstack: 0,
open:function(t, contenttype, contentsource, title, attr, recalonload){
    var d=dhtmlwindow //reference dhtmlwindow object
    this.interVeil=document.getElementById("interVeil") //Reference "veil" div
    this.veilstack++ //var to keep track of how many modal windows are open right now
    this.loadveil()
    if (recalonload=="recal" && d.scroll_top==0)
        d.addEvent(window, function(){dhtmlmodal.adjustveil()}, "load")
    var t=d.open(t, contenttype, contentsource, title, attr, recalonload)
    t.controls.firstChild.style.display="none" //Disable "minimize" button
    t.controls.onclick=function(){dhtmlmodal.close(this._parent, true)} //OVERWRITE default control action with new one
    t.show=function(){dhtmlmodal.show(this)} //OVERWRITE default t.show() method with new one
    t.hide=function(){dhtmlmodal.close(this)} //OVERWRITE default t.hide() method with new one

       $("#interVeil").click(function() {
            if (typeof emailwindow1 != "undefined" && dhtmlmodal.veilstack > 0) {
                dhtmlmodal.close(emailwindow1.controls._parent, true);
            }
            if (typeof emailwindow != "undefined" && dhtmlmodal.veilstack > 0) {
                dhtmlmodal.close(emailwindow.controls._parent, true);
            }
        });
return t
},


loadveil:function(){
    var d=dhtmlwindow
    d.getviewpoint()
    this.docheightcomplete=(d.standardbody.offsetHeight>d.standardbody.scrollHeight)? d.standardbody.offsetHeight : d.standardbody.scrollHeight
    this.interVeil.style.width=d.docwidth+"px" //set up veil over page
    this.interVeil.style.height=this.docheightcomplete+"px" //set up veil over page
    this.interVeil.style.left=0 //Position veil over page
    this.interVeil.style.top=0 //Position veil over page
    this.interVeil.style.visibility="visible" //Show veil over page
    this.interVeil.style.display="block" //Show veil over page
},

adjustveil:function(){ //function to adjust veil when window is resized
    if (this.interVeil && this.interVeil.style.display=="block") //If veil is currently visible on the screen
        this.loadveil() //readjust veil
},

closeveil:function(){ //function to close veil
    this.veilstack--
    if (this.veilstack==0) //if this is the only modal window visible on the screen, and being closed
        this.interVeil.style.display="none"
},


close:function(t, forceclose){ //DHTML modal close function
    t.contentDoc=(t.contentarea.datatype=="iframe")? window.frames["_iframe-"+t.id].document : t.contentarea //return reference to modal window DIV (or document object in the case of iframe
    if (typeof forceclose!="undefined")
        t.onclose=function(){return true}
    if (dhtmlwindow.close(t)) //if close() returns true
        this.closeveil()
},


show:function(t){
    dhtmlmodal.veilstack++
    dhtmlmodal.loadveil()
    dhtmlwindow.show(t)
}
} //END object declaration


document.write('<div id="interVeil"></div>')
dhtmlwindow.addEvent(window, function(){if (typeof dhtmlmodal!="undefined") dhtmlmodal.adjustveil()}, "resize")

/* End */


/* modal message.js */

/************************************************************************************************************
*    DHTML modal dialog box
*
*    Created:                        August, 26th, 2006
*    @class Purpose of class:        Display a modal dialog box on the screen.
*            
*    Css files used by this script:    modal-message.css
*
*    Demos of this class:            demo-modal-message-1.html
*
*     Update log:
*
************************************************************************************************************/


/**
* @constructor
*/

DHTML_modalMessage = function()
{
    var url;                                // url of modal message
    var htmlOfModalMessage;                    // html of modal message
    
    var divs_transparentDiv;                // Transparent div covering page content
    var divs_content;                        // Modal message div.
    var iframe;                                // Iframe used in ie
    var layoutCss;                            // Name of css file;
    var width;                                // Width of message box
    var height;                                // Height of message box
    
    var existingBodyOverFlowStyle;            // Existing body overflow css
    var dynContentObj;                        // Reference to dynamic content object
    var cssClassOfMessageBox;                // Alternative css class of message box - in case you want a different appearance on one of them
    var shadowDivVisible;                    // Shadow div visible ? 
    var shadowOffset;                         // X and Y offset of shadow(pixels from content box)
    var MSIE;
        
    this.url = '';                            // Default url is blank
    this.htmlOfModalMessage = '';            // Default message is blank
    this.layoutCss = 'modal-message.css';    // Default CSS file
    this.height = 200;                        // Default height of modal message
    this.width = 400;                        // Default width of modal message
    this.cssClassOfMessageBox = false;        // Default alternative css class for the message box
    this.shadowDivVisible = true;            // Shadow div is visible by default
    this.shadowOffset = 5;                    // Default shadow offset.
    this.MSIE = false;
    if(navigator.userAgent.indexOf('MSIE')>=0) this.MSIE = true;
    

}

DHTML_modalMessage.prototype = {
    // {{{ setSource(urlOfSource)
    /**
     *    Set source of the modal dialog box
     *     
     *
     * @public    
     */        
    setSource : function(urlOfSource)
    {
        this.url = urlOfSource;
        
    }    
    // }}}    
    ,
    // {{{ setHtmlContent(newHtmlContent)
    /**
     *    Setting static HTML content for the modal dialog box.
     *     
     *    @param String newHtmlContent = Static HTML content of box
     *
     * @public    
     */        
    setHtmlContent : function(newHtmlContent)
    {
        this.htmlOfModalMessage = newHtmlContent;
        
    }
    // }}}        
    ,
    // {{{ setSize(width,height)
    /**
     *    Set the size of the modal dialog box
     *     
     *    @param int width = width of box
     *    @param int height = height of box
     *
     * @public    
     */        
    setSize : function(width,height)
    {
        if(width)this.width = width;
        if(height)this.height = height;        
    }
    // }}}        
    ,        
    // {{{ setCssClassMessageBox(newCssClass)
    /**
     *    Assign the message box to a new css class.(in case you wants a different appearance on one of them)
     *     
     *    @param String newCssClass = Name of new css class (Pass false if you want to change back to default)
     *
     * @public    
     */        
    setCssClassMessageBox : function(newCssClass)
    {
        this.cssClassOfMessageBox = newCssClass;
        if(this.divs_content){
            if(this.cssClassOfMessageBox)
                this.divs_content.className=this.cssClassOfMessageBox;
            else
                this.divs_content.className='modalDialog_contentDiv';    
        }
                    
    }
    // }}}        
    ,    
    // {{{ setShadowOffset(newShadowOffset)
    /**
     *    Specify the size of shadow
     *     
     *    @param Int newShadowOffset = Offset of shadow div(in pixels from message box - x and y)
     *
     * @public    
     */        
    setShadowOffset : function(newShadowOffset)
    {
        this.shadowOffset = newShadowOffset
                    
    }
    // }}}        
    ,    
    // {{{ display()
    /**
     *    Display the modal dialog box
     *     
     *
     * @public    
     */        
    display : function()
    {
        if(!this.divs_transparentDiv){
            this.__createDivs();
        }    
        
        // Redisplaying divs
        this.divs_transparentDiv.style.display='block';
        this.divs_content.style.display='block';
        this.divs_shadow.style.display='block';        
        if(this.MSIE)this.iframe.style.display='block';    
        this.__resizeDivs();
        
        /* Call the __resizeDivs method twice in case the css file has changed. The first execution of this method may not catch these changes */
        window.refToThisModalBoxObj = this;        
        setTimeout('window.refToThisModalBoxObj.__resizeDivs()',150);
        
        this.__insertContent();    // Calling method which inserts content into the message div.
    }
    // }}}        
    ,
    // {{{ ()
    /**
     *    Display the modal dialog box
     *     
     *
     * @public    
     */        
    setShadowDivVisible : function(visible)
    {
        this.shadowDivVisible = visible;
    }
    // }}}    
    ,
    // {{{ close()
    /**
     *    Close the modal dialog box
     *     
     *
     * @public    
     */        
    close : function()
    {
        //document.documentElement.style.overflow = '';    // Setting the CSS overflow attribute of the <html> tag back to default.
        
        /* Hiding divs */
        this.divs_transparentDiv.style.display='none';
        this.divs_content.style.display='none';
        this.divs_shadow.style.display='none';
        if(this.MSIE)this.iframe.style.display='none';
        
    }    
    // }}}    
    ,
    // {{{ __addEvent()
    /**
     *    Add event
     *     
     *
     * @private    
     */        
    addEvent : function(whichObject,eventType,functionName,suffix)
    { 
      if(!suffix)suffix = '';
      if(whichObject.attachEvent){ 
        whichObject['e'+eventType+functionName+suffix] = functionName; 
        whichObject[eventType+functionName+suffix] = function(){whichObject['e'+eventType+functionName+suffix]( window.event );} 
        whichObject.attachEvent( 'on'+eventType, whichObject[eventType+functionName+suffix] ); 
      } else 
        whichObject.addEventListener(eventType,functionName,false);         
    } 
    // }}}    
    ,
    // {{{ __createDivs()
    /**
     *    Create the divs for the modal dialog box
     *     
     *
     * @private    
     */        
    __createDivs : function()
    {
        // Creating transparent div
        this.divs_transparentDiv = document.createElement('DIV');
        this.divs_transparentDiv.className='modalDialog_transparentDivs';
        this.divs_transparentDiv.style.left = '0px';
        this.divs_transparentDiv.style.top = '0px';
        
        document.body.appendChild(this.divs_transparentDiv);
        // Creating content div
        this.divs_content = document.createElement('DIV');
        this.divs_content.className = 'modalDialog_contentDiv';
        this.divs_content.id = 'DHTMLSuite_modalBox_contentDiv';
        this.divs_content.style.zIndex = 100000;
        
        if(this.MSIE){
            this.iframe = document.createElement('<IFRAME src="about:blank" frameborder=0>');
            this.iframe.style.zIndex = 90000;
            this.iframe.style.position = 'absolute';
            document.body.appendChild(this.iframe);    
        }
            
        document.body.appendChild(this.divs_content);
        // Creating shadow div
        this.divs_shadow = document.createElement('DIV');
        this.divs_shadow.className = 'modalDialog_contentDiv_shadow';
        this.divs_shadow.style.zIndex = 95000;
        document.body.appendChild(this.divs_shadow);
        window.refToModMessage = this;
        this.addEvent(window,'scroll',function(e){ window.refToModMessage.__repositionTransparentDiv() });
        this.addEvent(window,'resize',function(e){ window.refToModMessage.__repositionTransparentDiv() });
        

    }
    // }}}
    ,
    // {{{ __getBrowserSize()
    /**
     *    Get browser size
     *     
     *
     * @private    
     */        
    __getBrowserSize : function()
    {
        var bodyWidth = document.documentElement.clientWidth;
        var bodyHeight = document.documentElement.clientHeight;
        
        var bodyWidth, bodyHeight; 
        if (self.innerHeight){ // all except Explorer 
         
           bodyWidth = self.innerWidth; 
           bodyHeight = self.innerHeight; 
        }  else if (document.documentElement && document.documentElement.clientHeight) {
           // Explorer 6 Strict Mode          
           bodyWidth = document.documentElement.clientWidth; 
           bodyHeight = document.documentElement.clientHeight; 
        } else if (document.body) {// other Explorers          
           bodyWidth = document.body.clientWidth; 
           bodyHeight = document.body.clientHeight; 
        } 
        return [bodyWidth,bodyHeight];        
        
    }
    // }}}    
    ,
    // {{{ __resizeDivs()
    /**
     *    Resize the message divs
     *     
     *
     * @private    
     */    
    __resizeDivs : function()
    {
        
        var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

        if(this.cssClassOfMessageBox)
            this.divs_content.className=this.cssClassOfMessageBox;
        else
            this.divs_content.className='modalDialog_contentDiv';    
                    
        if(!this.divs_transparentDiv)return;
        
        // Preserve scroll position
        var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
        var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
        
        window.scrollTo(sl,st);
        setTimeout('window.scrollTo(' + sl + ',' + st + ');',10);

        this.__repositionTransparentDiv();
        

        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];
        
        // Setting width and height of content div
          this.divs_content.style.width = this.width + 'px';
        this.divs_content.style.height= this.height + 'px';      
        
        // Creating temporary width variables since the actual width of the content div could be larger than this.width and this.height(i.e. padding and border)
        var tmpWidth = this.divs_content.offsetWidth;    
        var tmpHeight = this.divs_content.offsetHeight;
        
        
        // Setting width and height of left transparent div
        
        

        
        
        
        this.divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';;
        this.divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';
        
         if(this.MSIE){
             this.iframe.style.left = this.divs_content.style.left;
             this.iframe.style.top = this.divs_content.style.top;
             this.iframe.style.width = this.divs_content.style.width;
             this.iframe.style.height = this.divs_content.style.height;
         }
         
        this.divs_shadow.style.left = (this.divs_content.style.left.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.top = (this.divs_content.style.top.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.height = tmpHeight + 'px';
        this.divs_shadow.style.width = tmpWidth + 'px';
        
        
        
        if(!this.shadowDivVisible)this.divs_shadow.style.display='none';    // Hiding shadow if it has been disabled
        
        
    }
    // }}}    
    ,
    // {{{ __insertContent()
    /**
     *    Insert content into the content div
     *     
     *
     * @private    
     */        
    __repositionTransparentDiv : function()
    {
        this.divs_transparentDiv.style.top = Math.max(document.body.scrollTop,document.documentElement.scrollTop) + 'px';
        this.divs_transparentDiv.style.left = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) + 'px';
        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];
        this.divs_transparentDiv.style.width = bodyWidth + 'px';
        this.divs_transparentDiv.style.height = bodyHeight + 'px';        
               
    }
    // }}}    
    ,
    // {{{ __insertContent()
    /**
     *    Insert content into the content div
     *     
     *
     * @private    
     */    
    __insertContent : function()
    {
        if(this.url){    // url specified - load content dynamically
            ajax_loadContent('DHTMLSuite_modalBox_contentDiv',this.url);
        }else{    // no url set, put static content inside the message box
            this.divs_content.innerHTML = this.htmlOfModalMessage;    
        }
    }        
}
/* End */

/* datepicker.js */


/**
This is a JavaScript library that will allow you to easily add some basic DHTML
drop-down datepicker functionality to your Notes forms. This script is not as
full-featured as others you may find on the Internet, but it's free, it's easy to
understand, and it's easy to change.

You'll also want to include a stylesheet that makes the datepicker elements
look nice. An example one can be found in the database that this script was
originally released with, at:

http://www.nsftools.com/tips/NotesTips.htm#datepicker

I've tested this lightly with Internet Explorer 6 and Mozilla Firefox. I have no idea
how compatible it is with other browsers.

version 1.5
December 4, 2005
Julian Robichaux -- http://www.nsftools.com

HISTORY
--  version 1.0 (Sept. 4, 2004):
Initial release.

--  version 1.1 (Sept. 5, 2004):
Added capability to define the date format to be used, either globally (using the
defaultDateSeparator and defaultDateFormat variables) or when the displayDatePicker
function is called.

--  version 1.2 (Sept. 7, 2004):
Fixed problem where datepicker x-y coordinates weren't right inside of a table.
Fixed problem where datepicker wouldn't display over selection lists on a page.
Added a call to the datePickerClosed function (if one exists) after the datepicker
is closed, to allow the developer to add their own custom validation after a date
has been chosen. For this to work, you must have a function called datePickerClosed
somewhere on the page, that accepts a field object as a parameter. See the
example in the comments of the updateDateField function for more details.

--  version 1.3 (Sept. 9, 2004)
Fixed problem where adding the <div> and <iFrame> used for displaying the datepicker
was causing problems on IE 6 with global variables that had handles to objects on
the page (I fixed the problem by adding the elements using document.createElement()
and document.body.appendChild() instead of document.body.innerHTML += ...).

--  version 1.4 (Dec. 20, 2004)
Added "targetDateField.focus();" to the updateDateField function (as suggested
by Alan Lepofsky) to avoid a situation where the cursor focus is at the top of the
form after a date has been picked. Added "padding: 0px;" to the dpButton CSS
style, to keep the table from being so wide when displayed in Firefox.

-- version 1.5 (Dec 4, 2005)
Added display=none when datepicker is hidden, to fix problem where cursor is
not visible on input fields that are beneath the date picker. Added additional null
date handling for date errors in Safari when the date is empty. Added additional
error handling for iFrame creation, to avoid reported errors in Opera. Added
onMouseOver event for day cells, to allow color changes when the mouse hovers
over a cell (to make it easier to determine what cell you're over). Added comments
in the style sheet, to make it more clear what the different style elements are for.
*/

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
 
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";        // common values would be "/" or "."
var defaultDateFormat = "mdy"    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
 
  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
 
  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;
 
  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;
 
  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
 
  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop ;
  }
 
  drawDatePicker(targetDateField, x, y);
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y)
{
  var dt = getFieldDate(targetDateField.value );
 
  // the datepicker table will be drawn inside of a <div> with an ID defined by the
  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
  // document we're working with, add one.
  if (!document.getElementById(datePickerDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
    var newNode = document.createElement("div");
    newNode.setAttribute("id", datePickerDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }
 
  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 10000;
 
  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();
 
  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
 
  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table cols=7 class='dpTable'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr class='dpTR'>";
  var TR_title = "<tr class='dpTitleTR'>";
  var TR_days = "<tr class='dpDayTR'>";
  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";
 
  // start generating the code for the calendar table
  var html = TABLE;
 
  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
  html += xTR;
 
  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayShort.length; i++)
    html += TD_days + dayArrayShort[i] + xTD;
  html += xTR;
 
  // now we'll start populating the table with days of the month
  html += TR;
 
  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;
 
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
    
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;
    
    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6)
      html += xTR + TR;
    
    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)
 
  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;
 
  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
  html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
  html += xTD + xTR;
 
  // and finally, close the table
  html += xTABLE;
 
  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }
 
  return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
 
  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
 
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
 
  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
 
  return dArray;
}

/**
Update the field with the given dateFieldName with the dateString that has been passed,
and hide the datepicker. If no dateString is passed, just close the datepicker without
changing the field value.

Also, if the page developer has defined a function called datePickerClosed anywhere on
the page or in an imported library, we will attempt to run that function with the updated
field as a parameter. This can be used for such things as date validation, setting default
values for related fields, etc. For example, you might have a function like this to validate
a start date field:

function datePickerClosed(dateField)
{
  var dateObj = getFieldDate(dateField.value);
  var today = new Date();
  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
 
  if (dateField.name == "StartDate") {
    if (dateObj < today) {
      // if the date is before today, alert the user and display the datepicker again
      alert("Please enter a date that is today or later");
      dateField.value = "";
      document.getElementById(datePickerDivID).style.visibility = "visible";
      adjustiFrame();
    } else {
      // if the date is okay, set the EndDate field to 7 days after the StartDate
      dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
      var endDateField = document.getElementsByName ("EndDate").item(0);
      endDateField.value = getDateString(dateObj);
    }
  }
}

*/
function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;
 
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.visibility = "hidden";
  pickerDiv.style.display = "none";
 
  adjustiFrame();
  targetDateField.focus();
 
  // after the datepicker has closed, optionally run a user-defined function called
  // datePickerClosed, passing the field that was just updated as a parameter
  // (note that this will only run if the user actually selected a date from the datepicker)
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
  
  // put a try/catch block around the whole thing, just in case
  try {
    if (!document.getElementById(iFrameDivID)) {
      // don't use innerHTML to update the body, because it can cause global variables
      // that are currently pointing to objects on the page to have bad references
      //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
      var newNode = document.createElement("iFrame");
      newNode.setAttribute("id", iFrameDivID);
      newNode.setAttribute("src", "javascript:false;");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      document.body.appendChild(newNode);
    }
    
    if (!pickerDiv)
      pickerDiv = document.getElementById(datePickerDivID);
    if (!iFrameDiv)
      iFrameDiv = document.getElementById(iFrameDivID);
    
    try {
      iFrameDiv.style.position = "absolute";
      iFrameDiv.style.width = pickerDiv.offsetWidth;
      iFrameDiv.style.height = pickerDiv.offsetHeight ;
      iFrameDiv.style.top = pickerDiv.style.top;
      iFrameDiv.style.left = pickerDiv.style.left;
      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } catch(e) {
    }
 
  } catch (ee) {
  }
 
}
/* End */

/* common.js */

var ns4 = document.layers;
var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1)||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1);
var agt=navigator.userAgent.toLowerCase();
var mac = (agt.indexOf("mac")!=-1);
var ie = (agt.indexOf("msie") != -1); 
var mac_ie = mac && ie;

var imageWin = null;

function getRealLeft(el) {
    xPos = el.offsetLeft;
    tempEl = el.offsetParent;
    while (tempEl != null) {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }
    return xPos;
}

function getRealTop(el) {
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while(tempEl != null){
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function showHideMenuNode(node_id, image_id){
    n = document.getElementById(node_id);
    i = document.getElementById(image_id);
    if(n){
        n.style.display = n.style.display == "none" ? "block" : "none";
        if(i){
            i.src = n.style.display == "none" ? skin_images + "/menu_tree_plus.gif" : skin_images + "/menu_tree_minus.gif";
        }
    }
}


function getElementHeight(Elem) {
    if(ns4){
        var elem = document.getElementById(Elem);
        return elem.clip.height;
    } else {
        if(document.getElementById) {
            var elem = document.getElementById(Elem);
        } else if (document.all){
            var elem = document.all[Elem];
        }
        if (op5) { 
            xPos = elem.style.pixelHeight;
        } else {
            xPos = elem.offsetHeight;
        }
        return xPos;
    } 
}

function getElementWidth(Elem) {
    if (ns4) {
        var elem = document.getElementById(Elem);
        return elem.clip.width;
    } else {
        if(document.getElementById) {
            var elem = document.getElementById(Elem);
        } else if (document.all){
            var elem = document.all[Elem];
        }
        if (op5) {
            xPos = elem.style.pixelWidth;
        } else {
            xPos = elem.offsetWidth;
        }
        return xPos;
    }
}


if(document.layers){
    _browser = "nn";
}
if(document.all){
    _browser = "ie";
}
if(navigator.userAgent.toLowerCase().match("gecko")){
    _browser= "gecko";
}
function isEmail(entry){
    var rex= /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/    
    return rex.test(entry);
}

function delay(gap){ /* gap is in millisecs */
    var then, now; 
    then = new Date().getTime();
    now = then;
    while((now-then) < gap){
        now=new Date().getTime();
    }
}

function showImage(image_url, image_width, image_height){
    image_width = image_width == "" ? 400 : image_width;
    image_height = image_height == "" ? 380 : image_height;

    var w = screen.width;
    var h = screen.height;
    var ww = image_width * 1 + 30;
    var wh = image_height * 1 + 45;
    var wx = (w - ww)/2;
    var wy = (h - wh)/2;
    
    if(imageWin != null){
        imageWin.close();
    }
    imageWin = null;
    imageWin = window.open(
        "", 
        "ProductImageWindow", 
        "titlebar=yes, toolbar=no, menubar=no, status=no, directories=no, resizable=yes, scrollbars=yes, top=" + wy.toString() + ", left=" + wx.toString() + ", width=" + ww.toString() + ", height=" + wh.toString() + ""
    );
    while(imageWin==null);
    imageWin.focus();
    
    imageWin.document.body.innerHTML = "";
    imageWin.document.write('<body style="padding:5px;margin:0px">');
    imageWin.document.write('<div align="center"><img hspace="0" vspace="0" src="' + image_url + '"></div><br/>');
    imageWin.document.write('<div align="center" style="font-family:arial;font-color:black;font-size:11px;"><a href="javascript:window.close();" style="color:#0000AA;">Close Window</a></div>');
    imageWin.document.write('</body>');
    imageWin.width = ww;
    imageWin.height = wh;
}

function showPrinterPage(url){
    var prWin = null;
    prWin = window.open(
        url,
        "PrintVer", 
        "titlebar=yes, toolbar=no, menubar=yes, status=yes, directories=no, resizable=yes, scrollbars=yes, top=20, left=20, width=810, height=600"
    );
    while(prWin==null);
    prWin.focus();
}

function OnButton(bt){
    document.images[bt].src = skin_images + bt + "_on.gif";
    
}
function OffButton(bt){
    document.images[bt].src = skin_images + bt + "_off.gif";
}

function OnMenu(cid){
    document.images["menul_" + cid].src = skin_images + "catl_bg_on.gif";
    document.all["menur_" + cid].background = skin_images + "catr_bg_on.gif";
}
function OffMenu(cid){
    document.images["menul_" + cid].src = skin_images + "catl_bg_off.gif";
    document.all["menur_" + cid].background = skin_images + "catr_bg_off.gif";
}

function OnMenu(img){
    document.images[img].src = skin_images + "menu_arrow_on.gif";
}
function OffMenu(img){
    document.images[img].src = skin_images + "menu_arrow.gif";
}

function ShowPopup(src){
    var bWin = null;
    bWin = window.open(
        src, 
        "PopupWind", 
        "titlebar=no, toolbar=no, menubar=no, status=no, directories=no, resizable=no, scrollbars=no, top=20, left=20, width=320, height=365"
    );
    while(bWin==null);
    bWin.focus();
}

function PopUpImage(image_source, image_width, image_height){
    var bWin = null;
    bWin = window.open(
        image_source, 
        "ImageWind", 
        "titlebar=no, toolbar=no, menubar=no, status=no, directories=no, resizable=no, scrollbars=no, top=20, left=20, width=" + (image_width + 20) + ", height=" + (image_height + 20)
    );
    while(bWin==null);
    bWin.focus();
}

function ConfirmLogout(){
    if(orderItemsCount > 0){
        if(confirm("You have items in your cart. Logging out will empty your cart\nAre you sure want to continue?")){
            document.location = urlLogout;
        }
    }
    else{
        if(confirm("Do you really want to logout?")){
            document.location = urlLogout;
        }
    }
}

function CartConfirmDeleteItem(ocid){
    if(confirm(msg_confirm_delete_item)){ 
        document.location = CartDeleteItemUrl + '&ocid=' + ocid;
    }
}
function CartConfirmEmpty(){
    if(confirm(msg_confirm_empty_cart)){
        document.location = CartEmptyUrl;
    }
}


     function LTrim(str)
     {
         if(str==null)
        {
            return str;
        }
        for(var i=0;str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t";i++);
        return str.substring(i,str.length);
     }

    

     function RTrim(str)
     {
         if(str==null)
        {
            return str;
        }
        for(var i=str.length-1;str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t";i--);
        return str.substring(0,i+1);
     }
  

     function Trim(str)
     {
         return LTrim(RTrim(str));
     }

/* End */


/* md5.js */

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

/* End */
