// total_price is defined as global var, becouse it is also used in coupon's js'
var total_price;

jQuery(document).ready( function() {
    set_add_del();
    total_price= 0;
    jQuery('#product_list input:checkbox').click(function(){
        var item_id = jQuery(this).val();
        var item_price = jQuery('#item_'+item_id+' span.item_price').html();
        if(jQuery(this).attr("checked")){
            total_price += parseFloat(item_price.substring(1, item_price.length));
        }else{
            total_price -= parseFloat(item_price.substring(1, item_price.length));
        }
        //Added by Nemi
        var total = Math.round(total_price*100)/100;
        //
        jQuery('#total_amount b').html('$'+total);
    });

    jQuery('#submit_paypal').click(function(){
        //            var count = 1;
        var final_item_ids = '';
        var final_item_prices = '';
        var final_item_names = '';
        var final_coupon_code = '';

        jQuery('#product_list input:checkbox').each(function(i){
            if(jQuery(this).attr("checked")){
                var item_id = jQuery(this).val();
                var item_price = jQuery('#item_'+item_id+' span.item_price').html();
                item_price = parseFloat(item_price.substring(1, item_price.length));
                var item_name = jQuery('#item_'+item_id+' span.item_name').html();
                final_item_ids += item_id + '|';
                final_item_prices += item_price + '|';
                final_item_names += item_name + '|';

                //if(jQuery('#item_'+item_id+' span.coupon_code_hidden').length >0) {
                var coupon_code = jQuery('#item_'+item_id+' span.coupon_code_hidden').html();
                final_coupon_code += coupon_code  + '|';
            //}
            }
        });
        var all_coupon = jQuery('#all_coupon').html();
        var coupon_disc = jQuery('#coupon_disc').html();

        final_item_ids = final_item_ids.substring(0,final_item_ids.length-1);
        final_item_prices = final_item_prices.substring(0,final_item_prices.length-1);
        final_item_names = final_item_names.substring(0,final_item_names.length-1);

        if(final_coupon_code.length >0) {
            final_coupon_code = '&coupon_disc='+coupon_disc+'&all_coupon='+all_coupon+'&coupon_code='+final_coupon_code.substring(0,final_coupon_code.length-1);
        }

        if (final_item_ids != '') {
            jQuery.ajax({
                type: "POST",
                //Changed By NEMI
                url: wpsa_var.admin_ajax_php,
                data: 'action=product_form&item_id='+ final_item_ids + '&item_price=' + final_item_prices + '&item_name=' + final_item_names+final_coupon_code,
                success: function(msg){
                    jQuery("#rt_sa_product_hidden_form").parent().remove();
                    jQuery(msg).appendTo('body').hide();
                    jQuery("#rt_sa_product_hidden_form").submit();
                }
            });
        }
    });

    jQuery('#product').change(function(){
        //console.log(jQuery(this).val());
        //alert('hello');

//changes 17 march 2011 by Santosh
        jQuery.ajax({
            type: "POST",
            url: wpsa_var.admin_ajax_php,
//            data: jQuery(this).serializeArray()+'&action=wpsa_product_reset',
            data: jQuery(this).serialize()+'&action=wpsa_product_reset',
            beforeSend: function(obj) {
                jQuery('#domain_block').html('<img id="loading" src="'+wpsa_var.plugindir+'/img/loading.gif">');
            } ,
            success: function(data){
                jQuery('#domain_block').html(data);
                //set options
                var options = {
                    target:        '#domain_block'   // target element(s) to be updated with server response
                };
            }
        });

//        jQuery.ajax({
//            url : wpsa_var.plugindir +  '/php/wp-sa-product-ajax.php?pid='+jQuery(this).val(),
//            dataType: 'html',
//            beforeSend: function(obj) {
//                jQuery('#domain_block').html('<img id="loading" src="'+wpsa_var.plugindir+'/img/loading.gif">');
//            } ,
//            success : function(data) {
//                jQuery('#domain_block').html(data);
//
//                //set options
//                var options = {
//                    target:        '#domain_block'   // target element(s) to be updated with server response
//                };
//            }
//        });	//end of ajax
    });

    // validate signup form on keyup and submit
    var validator = jQuery("#product_form").validate({
        rules: {
            name: "required",
            price: {
                required: true,
                number: true
            },
            product_file: {
            //required: true
            },
            select_type:{
                required:true
            }
        },

        // the errorPlacement has to take the table layout into account
        errorPlacement: function(error, element) {
            if ( element.is(":radio") )
                error.appendTo( element.parent().next().next() );
            else if ( element.is(":checkbox") )
                error.appendTo ( element.next() );
            else
                error.appendTo( element.parent().next() );
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").removeClass("error");
        //label.html("&nbsp;").addClass("checked");
        }
    });

    // validate add subscription form
    jQuery("#subscription_form").validate({
        rules: {
            name: "required",
            amount3: "required",
            duration3: "required"
        },

        errorPlacement: function(error, element) {
            if ( element.is(":radio") )
                error.appendTo( element.parent().next().next() );
            else if ( element.is(":checkbox") )
                error.appendTo ( element.next() );
            else
                error.appendTo( element.parent().next() );
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            label.html("&nbsp;").removeClass("error");
        }
    });

    // validate add subscription sales log
    jQuery("#add-subsc-sales").validate({
        rules: {
            wpsa_user_name: "required",
            email: {
                required: true,
                email: true
            },
            tx_id: "required",
            sub_id: "required"
        },

        errorPlacement: function(error, element) {
            if ( element.is(":radio") )
                error.appendTo( element.parent().next().next() );
            else if ( element.is(":checkbox") )
                error.appendTo ( element.next() );
            else
                error.appendTo( element.parent().next() );
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            label.html("&nbsp;").removeClass("error");
        }
    });



    var validator = jQuery("#SalesAutomator-Conf").validate({
        rules: {
            rt_sa_paypal_pdt: "required",
            epp_payment_email: {
                required: true,
                email: true
            }
        },

        // the errorPlacement has to take the table layout into account
        errorPlacement: function(error, element) {
            error.prependTo( element.parent() );
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").removeClass("error");
        //label.html("&nbsp;").addClass("checked");
        }
    });

    //validation for buy product form
    var validator = jQuery("#wp-cart").validate({
        rules: {
            name: "required",
            os0: {
                required: true,
                email: true
            },
            os1: {
                required: true ,
                url: true
            }
        },

        // the errorPlacement has to take the table layout into account
        errorPlacement: function(error, element) {
            if ( element.is(":radio") )
                error.appendTo( element.parent().next().next() );
            else if ( element.is(":checkbox") )
                error.appendTo ( element.next() );
            else
                error.appendTo( element.parent().next() );
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").addClass("checked");
        }
    });

    //validation for buy product form
    var validator = jQuery("#wp-retrive").validate({
        rules: {
            email: {
                required: true,
                email: true
            },
            domain_name: {
                required: true ,
                url: true
            }
        },

        // the errorPlacement has to take the table layout into account
        errorPlacement: function(error, element) {
            if ( element.is(":radio") )
                error.appendTo( element.parent().next().next() );
            else if ( element.is(":checkbox") )
                error.appendTo ( element.next() );
            else
                error.appendTo( element.parent().next() );
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").addClass("checked");
        }
    });

    /**
         *to handel paypal subscrrption form
         */
    jQuery('#rt_sa_subscription_button').click(function () {
        // rt_sa_rp stands for recurring payment
        var rt_sa_rp = 'yes' ;

        jQuery("input:radio.recurring_select").each(function(i){
            if(jQuery(this).attr("checked")){
                rt_sa_rp = jQuery(this).val();
            }
        });
        jQuery('#subscription_form_list input:radio').each(function(i){
            if(jQuery(this).attr("checked")){
                var item_id = jQuery(this).val();
                jQuery.ajax({
                    type: "POST",
                    //Changed By NEMI
                    url: wpsa_var.admin_ajax_php,
                    data: 'action=subscription_form&item_id='+ item_id + '&rt_sa_recurring=' + rt_sa_rp,
                    success: function(msg){
                        jQuery("#rt_sa_subsription_hidden_form").parent().remove();
                        jQuery(msg).appendTo('body').hide();
                        jQuery("#rt_sa_subsription_hidden_form").submit();
                    }
                });

            }
        });
    }); // end of paypal subscrrption form
});	//end of doc ready

function rt_search_focus(){
    var rt_searchtext = jQuery('#rt_searchbox').val();
    if(rt_searchtext == 'Enter a keyword to search...'){
        jQuery('#rt_searchbox').val('');
    }
}

/**
     * deactivate transaction record
     */
function rt_change_status(curr_action, row_id) {
    jQuery.ajax({
        url: wpsa_var.admin_ajax_php,
        type: 'POST',
        data: 'action='+ curr_action +'&row_id='+row_id,
        success:function(){
            location.reload(true);
        }
    });

}

function set_add_del(){

    jQuery('.remove_row').show();
    jQuery('.add_row').hide();
    jQuery('.add_row:last').show();
    jQuery(".row_block:only-child  .remove_row").hide();
//            jQuery('.row_block:first .remove_row').hide();
}

function selrem(clickety){
    jQuery(clickety).parent().remove();
    set_add_del();
    return false;
}

function seladd(clickety){
    jQuery('.row_block:last').after(
        jQuery('.row_block:last').clone()
        );
    jQuery('.row_block:last input').attr('value', '');
    var title = jQuery('.row_block:last input#product_file').attr('name');
    var title_split1 = title.split("[");
    var title_split2 = title_split1[1].split("]");
    var index = parseInt(title_split2[0]) + 1;
    title = title_split1[0] + '[' + index + ']';

    //jQuery('.row_block:last input.rt_img').attr('name', title);

    set_add_del();
    return false;
}
    