// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var CBW = {
	showProductDetails: function(product_id)
	{
		jQuery('#results_container').hide()
		jQuery('#itemdesciption_' + product_id).show()
		return false;
	},

	showSearchResults: function(product_id)
	{
		jQuery('#itemdesciption_' + product_id).hide()
		jQuery('#results_container').show()
		return false;
	},

	clickCategory: function(div_id, category_id)
	{
		jQuery('a.btn').removeClass('btn_highlight');
		jQuery('#'+div_id).toggle("fast");
		jQuery('#'+div_id).parent().children('a.btn').addClass('btn_highlight');
		jQuery('#category_id').val(category_id);
		return false;
	},

    // Please make sure that the objects are obtained using jquery or prototype, when these things start to work.
    enableLossTypeOther: function(select, input_id)
    {
         var selectedValue = select.options[select.selectedIndex].value;
         if (selectedValue.toLowerCase() == "other")
         {
             document.getElementById(input_id).removeAttribute("disabled");
             document.getElementById(input_id).focus();
         }
         else
         {
             document.getElementById(input_id).setAttribute("disabled","disabled");
         }
    },

    enableLossAddressOther: function(select, input_id)
    {
        
	  var selectedValue = select.options[select.selectedIndex].value;
       
         if (selectedValue.toLowerCase() == "other")
         {
       
	      document.getElementById(input_id).removeAttribute("disabled");
             document.getElementById(input_id).focus();
         }
         else
         {
             document.getElementById(input_id).setAttribute("disabled","disabled");
         }
    },

    
    addZeroToFront: function(number)
    {
        if(number.indexOf(".")== 0)
        {
            number = "0" + number;
        }
        return number;
    },

    precalculateDepreciatedPrice: function(item_id, year)
    {  
    if (item_id === "" || year === "") return;
        
        var depreciation_entry_id = document.getElementById('claim_item_depreciation_entry_id').value  

        if (!CBW.isInteger(depreciation_entry_id))
        {
           jQuery("#depreciation_price_" + item_id).hide();
        } else {        
           jQuery("#depreciation_price_" + item_id).show();
        }

  	 var tax_value1 = CBW.addZeroToFront($('claim_item_tax').value);       
        var is_taxable_value1 = '';    
           
        if ( $('claim_item_is_taxable') != null)
        {
             is_taxable_value1 = $('claim_item_is_taxable').value;
        }
        else
        {       
             is_taxable_value1 = $('is_taxable_value_hidden').value;        
        }

	 //alert(is_taxable_value1);
       // alert(tax_value1); 

        var dep_rate = $('depreciation_rate').value;
        var depreciation_max_rate =  $('depreciation_max_rate').value;
        if (depreciation_max_rate == '')
        {
            depreciation_max_rate = 0;
        }
        var unit_price = CBW.addZeroToFront($('claim_item_unit_price').value);

        var quantity = $('claim_item_quantity').value;
        var div_id = 'depreciation_price_'+item_id;
        var usage = this.getSelectedUsage(item_id);

        var the_year = year;
        var entered_year = $('claim_item_year').value;

        if(this.isInteger(entered_year))
        {
          the_year = entered_year;
        }

        if((CBW.isInteger(depreciation_entry_id) || CBW.isInteger(dep_rate)) && CBW.isInteger(quantity))
        {
           // alert(quantity);
		new Ajax.Updater({success: div_id, failure: null},
                        "/claim_items/precalculate_price/?id="+item_id+"&claim_item[depreciation_entry_id]="
                            + depreciation_entry_id+"&year="+the_year+"&claim_item[usage]="+usage+"&claim_item[overriden_depreciation_rate]="+dep_rate
                            +"&claim_item[tax]="+tax_value1+"&claim_item[unit_price]="+unit_price+"&claim_item[quantity]=" + quantity+"&depreciation_max_rate=" + depreciation_max_rate,
                        {method: 'get', evalScripts:true, asynchronous:true});
        } 
	
	
    },

    recalculateTaxRate: function()
    {       
        var tax_value = CBW.addZeroToFront($('claim_item_tax').value);         
        var unit_price = CBW.addZeroToFront($('claim_item_unit_price').value);

        if(CBW.isFloat(tax_value) && CBW.isFloat(unit_price))
        {
            tax_rate = tax_value * 100 / unit_price;
            jQuery('#claim_item_tax_rate').val((Math.round(tax_rate*100)/100).toFixed(2));
        }        
    },
    
    recalculateTax: function()
    {      
        var tax_rate = CBW.addZeroToFront($('claim_item_tax_rate').value);         
        var unit_price = CBW.addZeroToFront($('claim_item_unit_price').value);

        if(CBW.isFloat(tax_rate) && CBW.isFloat(unit_price))
        {
            tax_value = unit_price * tax_rate / 100;
            jQuery('#claim_item_tax').val((Math.round(tax_value*100)/100).toFixed(2));
        }        
    },
    
    toggleTaxable:  function(selected_value)
    {   
        if ($('replacement') != null)
        {
            if (selected_value == 'true')
            {            
                $('tax_amount_fieldset').style.display = '';
                $('tax_rate_fieldset').style.display = '';      
                this.recalculateTax();
            }
            else
            {          
                $('tax_amount_fieldset').style.display = 'none';
                jQuery('#claim_item_tax').val('0.00');
                $('tax_rate_fieldset').style.display = 'none';
                jQuery('#claim_item_tax_rate').val('0.00');
            }
        }
    },
    
    recalculateRCV:  function()
    {        
        if ($('replacement') != null)
        {       
            var tax_value = CBW.addZeroToFront($('claim_item_tax').value);       
            var unit_price_value = CBW.addZeroToFront($('claim_item_unit_price').value);
            var shipping_value = CBW.addZeroToFront($('claim_item_shipping').value);
            
            var is_taxable_value = '';    
           
            if ( $('claim_item_is_taxable') != null)
            {
                is_taxable_value = $('claim_item_is_taxable').value;
            }
            else
            {       
                is_taxable_value = $('is_taxable_value_hidden').value;        
            }
            
            var quantity_value = '';            
            if ( $('claim_item_quantity') != null)
            {
                quantity_value = $('claim_item_quantity').value;
            }
            else
            {
                quantity_value = $('quantity_value_hidden').value;               
            }
            
            if (shipping_value == '') 
            {shipping_value = '0.00';}
             
            if (is_taxable_value == 'true' )
            {                    
                if (CBW.isFloat(unit_price_value) && CBW.isFloat(shipping_value) && CBW.isFloat(tax_value) && CBW.isInteger(quantity_value))
                {               
                    rcv_value = (parseFloat(unit_price_value) + parseFloat(shipping_value) + parseFloat(tax_value)) * parseInt(quantity_value)
                    $('rcv').innerHTML = '$' + (Math.round(rcv_value*100)/100).toFixed(2);
                }
            }
            else
            {                
                if (CBW.isFloat(unit_price_value) && CBW.isFloat(shipping_value) && CBW.isInteger(quantity_value))
                {
                    rcv_value = (parseFloat(unit_price_value) + parseFloat(shipping_value)) * parseInt(quantity_value)                   
                    $('rcv').innerHTML = '$' + Math.round(rcv_value*100)/100
                }
            }
        }
    },
    
    getSelectedUsage: function(item_id)
    {
      var usage = 'medium'

      if($("low_usage_"+item_id).checked)
      {
        usage = "low"
      }

      if($("high_usage_"+item_id).checked)
      {
        usage = "high"
      }

      return usage
    },
     updateClaimTotal: function(claim_id)
    {
        new Ajax.Request("/claim_items/claim_total/?claim_id="+claim_id, {method: 'get', evalScripts: false,
            onSuccess: function(resp) {
                var text = resp.responseText.strip();
                $('claim_total').innerHTML = text;
            }});
    },
    
    copyOrganizationAddress: function()
    {  
        jQuery("#branch_address_line_1").val(jQuery("#organization_address_line_1").val());
        jQuery("#branch_address_line_2").val(jQuery("#organization_address_line_2").val());
        jQuery("#branch_city").val(jQuery("#organization_city").val());
        jQuery("#branch_state").val(jQuery("#organization_state").val());
        jQuery("#branch_zip").val(jQuery("#organization_zip").val());
    },
    
    copyAddress: function()
    {  

       jQuery("#policy_holder_address_line3").val(jQuery("#policy_holder_address_line1").val());
	jQuery("#policy_holder_address_line4").val(jQuery("#policy_holder_address_line2").val());
	jQuery("#policy_holder_city1").val(jQuery("#policy_holder_city").val());
	jQuery("#policy_holder_state1").val(jQuery("#policy_holder_state").val());
	jQuery("#policy_holder_zip1").val(jQuery("#policy_holder_zip").val());

    },

    copyOrganizationContactInfo: function()
    {
        //jQuery("#branch_primary_contact_first_name").val(jQuery("#organization_primary_contact_first_name").val());
        //jQuery("#branch_primary_contact_last_name").val(jQuery("#organization_primary_contact_last_name").val());
        //jQuery("#branch_primary_contact_phone").val(jQuery("#organization_primary_contact_phone").val());
        jQuery("#branch_email").val(jQuery("#organization_email").val());
    },
    
    createBreadcrumbs: function(id)
    {
		jQuery("#breadcrumbs").load("/breadcrumbs/create_breadcrumbs/", {category_id: id});
//        var div_id = 'breadcrumbs';       
//        new Ajax.Updater({success: div_id, failure: null},
//                        "/breadcrumbs/create_breadcrumbs/?category_id="+id, {method: 'get', evalScripts:true, asynchronous:true});
    },

    isInteger: function(string)
    {
      var anum=/(^\d+$)/
      return anum.test(string)
    },

    isFloat: function(string)
    {
      var anum=/(^\d+$)|(^\d+\.\d+$)/
      return anum.test(string)
    },
    
    setUserAction: function(obj, adjustor_id, is_adjustor_active, is_branch_admin, authorizable_id, user_id)
    {
        if (obj.value == 'activate_deactivate')
        {
          var action_name = is_adjustor_active == 'true' ? 'deactivate_adjustor' :  'activate_adjustor';
          var confirm_message = is_adjustor_active == 'true' ? 'Are you sure you wish to deactivate this user?' : 'Are you sure you wish to activate this user?'
          if (confirm(confirm_message)) { 
              new Ajax.Request('/organization/'+action_name+'/'+adjustor_id+'?branch_id='+authorizable_id, {asynchronous:true, evalScripts:true}); 
               obj.selectedIndex = 0;
            }
          return false;
        }
        else if (obj.value == 'change_role')
        {
            var confirm_message = is_branch_admin == 'true' ? 
                            'Are you sure you wish to remove the branch admin role from this user ?' 
                            : 'Are you sure you wish to grant this user the branch admin role?'
            var action_name = (is_branch_admin == 'true') ? 'remove_branch_admin_role' :  'add_branch_admin_role';
            if (confirm(confirm_message)) { 
              new Ajax.Request('/organization/'+action_name+'?user_id='+user_id+'&branch_id='+authorizable_id, {asynchronous:true, evalScripts:true}); 
              obj.selectedIndex = 0;
            } 
           return false;
        }   
        else if (obj.value == 'reset_password')
        {
            var confirm_message = 'Are you sure you wish to reset the password for this user ?' 
            if (confirm(confirm_message)) { 
              new Ajax.Updater('notice_message','/user_manager/reset_password/'+user_id, {asynchronous:true, evalScripts:true}); 
              obj.selectedIndex = 0;
            } 
           return false;
        } 
        else if (obj.value == 'set_primary_org_admin')
        {
            var confirm_message = 'Are you sure you wish to set this user as primary contact ?' 
            if (confirm(confirm_message)) { 
              window.location.href = '/organization/set_primary_org_admin?org_id='+authorizable_id+'&user_id='+user_id;
            } 
           return false;
        } 
        else if (obj.value == 'set_primary_branch_admin')
        {
            var confirm_message = 'Are you sure you wish to set this user as primary contact ?' 
            if (confirm(confirm_message)) { 
              window.location.href = '/organization/set_primary_branch_admin?branch_id='+authorizable_id+'&user_id='+user_id;
            } 
           return false;
        }
        else if (obj.value == 'log_out_user')
        {
            var confirm_message = 'Are you sure you wish to log out this user ?'
            if (confirm(confirm_message)) {
              new Ajax.Updater('notice_message','/user_manager/log_out_user/'+user_id, {asynchronous:true, evalScripts:true});
              obj.remove(obj.selectedIndex);
              obj.selectedIndex = 0;
            }
           return false;
        }
        return null;
    },
    showPaymentPlan : function(payment_type_id)
    {
         new Ajax.Updater('payment_plan','/organization/show_payment_plan/' + payment_type_id, {asynchronous:true, evalScripts:true}); 
             
    },
    showPriceRangeInfo : function(price_range_type)
    {
         new Ajax.Updater('price_range_info','/organization/show_price_range_info/?type=' + price_range_type, {asynchronous:true, evalScripts:true}); 
             
    },
    insertNextPrice : function(index)
    {
        /* added some error checking --
         * CAVEAT: if user enters data in wrong order, can potentially have invalid ranges with no
         * errors displayed. this is because only the current row is checked and not the entire form. */
        var i = parseInt(index);
        if (isNaN(i)) { /* just in case */
            alert("insertNextPrice: [Error] index must be a number");
            return;
        }
        var currentEnd = jQuery("#price_range_" + i +"_range_end");
        var currentStart = jQuery("#price_range_" + i +"_range_start");
        var next = jQuery("#price_range_" + (i + 1) + "_range_start");

        var currentEndValue = parseInt(currentEnd.val());
        var currentStartValue = parseInt(currentStart.val());

        /* a convenience function to set or clear errors */
        function error(jqueryObj, errorString) {
            /* Sets Error on field with errorString.
            If errorString is undefined or explicitly false, error is removed */
            if (errorString === undefined || errorString === false) { /* we don't want type coercion */
                jqueryObj.removeAttr("style");
                jqueryObj.val("");
            }
            else {
                jqueryObj.attr("style", "color: red;");
                jqueryObj.val(errorString);
            }
        }

        var okToProcess = true;

        if (isNaN(currentEndValue)) {
            error(currentEnd, "Invalid Range");
            okToProcess = false;
        }

        if (isNaN(currentStartValue)) {
            /* this should never happen, but we'll check out of paranoia */
            error(currentStart, "Invalid Range");
            okToProcess = false;
        }

        if (!okToProcess) return;

        if (currentStartValue < 0) {
            /* this should never happen, but we'll check out of paranoia */
            error(currentStart, "Must be a positive number");
            okToProcess = false;
        }

        if (currentEndValue < 0) {
            error(currentEnd, "Must be a positive number");
            okToProcess = false;
        }

        if (!okToProcess) return;

        if (currentStartValue >= currentEndValue) {
            error(currentEnd, "Must be a larger integer");
            return;
        }

        /* clear all errors */
        error(currentEnd);
        error(currentStart);
        error(next);

        /* make sure these are integers and not floats */
        currentEnd.val(currentEndValue);
        currentStart.val(currentStartValue);

        if (!!next.length) next.val(currentEndValue + 1);
    },
    putNextPrice : function(i, obj)
    {
       if (!isNaN(obj.value)){
        next = jQuery("#price_ranges_"+(i+1)+"_range_start")
        next.val(parseInt(obj.value)+1)
        }
       
    }
} // END CBW
