$(document).ready(function(){
    // Show or hide the fabric collar collar 
    $("#prod-detail-size").change(function(){
        if($("#prod-detail-size").val() != 0) {
            jQuery.ajax({
                url: '/ajax.php',
                type: 'GET',
                data: 'cb=' + Math.floor(Math.random()*99999999999) + '&size=' + $("#prod-detail-size").val() + '&prod_id=' + $("#prod-id").val(),
                dataType: 'text',
                success: function(data) {
                    decoded = eval('(' + data + ')');
                    if(decoded.nylon_color != undefined) {
                        $("#prod-nylon-color").html(decoded.nylon_color);
                        if(decoded.nylon_color_images != undefined) {
                            $(".select_nylon").html(decoded.nylon_color_images);
                        }
                        $("#p-prod-price").html('');
                        $('#prod_ind_price').val('');
                        $('#prod-price-template-id').val('');
                        /*$('#prod-nylon-color').bind('change', function () {
                            handleNylonColorChange();
                        });
                        handleNylonColorChange();*/
                    }
                    
                    if(decoded.nylon_item != undefined) {
                        $("#prod-nylon-item").html(decoded.nylon_item);
                        $("#p-prod-price").html('');
                        $('#prod_ind_price').val('');
                        $('#prod-price-template-id').val('');
                        $('#prod-nylon-item').bind('change', function() {
                            handleNylonItemChange();
                        });
                    }
                    
                    if(decoded.fabric_buckle_type != undefined) {
                        $("#prod-fabric-buckle-type").html(decoded.fabric_buckle_type);
                        $("#p-prod-price").html('');
                        $('#prod_ind_price').val('');
                        $('#prod-price-template-id').val('');
                        $('#prod-fabric-buckle-type').bind('change', function() {
                            handleFabricBuckleTypeChange();
                        });
                    }
                    
                    if(decoded.nylon_color == undefined && decoded.nylon_item == undefined && decoded.fabric_buckle_type == undefined) {
                        //reset all other div's
                        // Nylon
                        $("#prod-nylon-item").html('');
                        $("#prod-nylon-color").html('');
                        $('.select_nylon').html('');
                        // Common
                        $("#p-prod-price").html('');
                        $('#prod_ind_price').val('');
                        $('#prod-price-template-id').val('');
                        $("#p-prod-price").html('<p><label>Product Not Available!</label></p>');
                    }
                    
                    $("a.fancybox").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 500, 'zoomSpeedOut': 500 });
                }
            });
            
            // reset the fields and div's which are not directly dependent on the size
            $("#prod-buckle-type").html('');
            $("#prod-nylon-buckle-color").html('');
            $('.buckle_color_wrap').hide('slow', function() {});
            // Fabric part
            $("#prod-fabric-buckle-type").html('');
            $("#prod-fabric-buckle-color").html('');
            $('#prod-price-template-id').val('');
        } else {
            //reset all other div's
            // Fabric part
            $("#prod-fabric-buckle-type").html('');
            $("#prod-fabric-buckle-color").html('');
            // Nylon
            $("#prod-nylon-item").html('');
            $("#prod-buckle-type").html('');
            $("#prod-nylon-buckle-color").html('');
            $("#prod-nylon-color").html('');
            $('.select_nylon').html('');
            // Common
            $("#p-prod-price").html('');
            $('#prod_ind_price').val('');
            $('#prod-price-template-id').val('');
            $('.buckle_color_wrap').hide('slow', function() {});
        }
    });
    
    $('#qty').keyup(function() {
        if($('#prod_ind_price').val() != 'NA' && !isNaN($('#prod_ind_price').val())) {
            var rawPrice = truncate(parseFloat($('#prod_ind_price').val() * $('#qty').val()));
            $('#p-prod-price').html('<label style="padding-top:5px;">Price: $' + rawPrice + '</label>');
        }
    });
    
    $('#i-comm-prod-add').click(function() {
        if(isNaN($('input[name="qty"]').val()) || $('input[name="qty"]').val() == '' || parseInt($('input[name="qty"]').val()) <= 0) {
            alert('Please Provide a quantity.');
            $('input[name="qty"]').focus();
            return false;
        }
        
        if($('#prod-price-template-id').val() == '' && $('#prod-ws-price-template-id').val() == '') {
            alert('Please Fill All The Fields');
            return false;
        }
        
        // Add validation codes for the daisy pop tags
        // Needed values will be passed from i-comm module
        if(typeof(TAG_TYPE) != 'undefined' && TAG_TYPE == 'daisy_pop') {
            if($('#prod-option-' + daisy_pop_size).val() == '') {
                  alert('Please select a Size.');
                  return false;
              }
              
              if($('#prod-option-' + daisy_pop_shape).val() == '') {
                  alert('Please select a Shape.');
                  return false;
              }
              
              if($.trim($('#prod-option-' + daisy_pop_eng_front).val()) == ''){
                  alert('Please Specify Engraving Front.');
                  $('#prod-option-' + daisy_pop_eng_front).focus();
                  return false;
              }
              
              if($.trim($('#prod-option-' + daisy_pop_eng_back).val()) == ''){
                  alert('Please Specify Engraving Back.');
                  $('#prod-option-' + daisy_pop_eng_back).focus();
                  return false;
              }
              
              // Engraving options comes here
              if($('#prod-option-' + daisy_pop_eng_front).attr('maxlength') < $('#prod-option-' + daisy_pop_eng_front).val().length) {
                  alert('Maximum Characters allowed for Engraving Front are ' + $('#prod-option-' + daisy_pop_eng_front).attr('maxlength'));
                  $('#prod-option-' + daisy_pop_eng_front).focus();
                  return false;
              }
              
              if($('#prod-option-' + daisy_pop_eng_back).attr('maxlength') < $('#prod-option-' + daisy_pop_eng_back).val().length) {
                  alert('Maximum Characters allowed for Engraving Back are ' + $('#prod-option-' + daisy_pop_eng_back).attr('maxlength'));
                  $('#prod-option-' + daisy_pop_eng_back).focus();
                  return false;
              }

              return true;
        }
        
        if(typeof(PRODUCT_TYPE) != 'undefined' && PRODUCT_TYPE == 'cr_stripe') {
            var ret = true;
            $('select').each(function(index) {
                var id = '#' + $(this).attr('id');
                if($(id).val() == '' && $(id).attr('disabled') != true) {
                    var field = $(id + ' option[value=""]').text();
                    alert('Please ' + field);
                    ret = false;
                    return false;
                }
            });

            return ret;
        }
        
    });
    
    // Handle the fav button click
    $('.add_to_fav').click(function(event) {
        $('#div-fav-hide').html('<input type="hidden" id="i-comm-favorite" name="i-comm-favorite" value="Add to Favorites">');
        $('#prod-form').submit();
        event.preventDefault();
    });
    
    // hook to daisy dog tag validator
    if(typeof(TAG_TYPE) != 'undefined' && TAG_TYPE == 'daisy_pop') {
        $('#prod-option-' + daisy_pop_size).change(function() {
            handleDaisyPopTagSizeChange();
        });
    }
    
    // hook to red dingo dog tag design check for star & stripes
    if(typeof(TAG_TYPE) != 'undefined' && TAG_TYPE == 'red_dingo') {
        $('#prod-option-' + red_dingo_dog_tag_design).change(function() {
            handleRedDingoDogTagDesignChange();
        });
    }
    
    if(typeof(create_stripe_buckle_type_id) != 'undefined' && PRODUCT_TYPE == 'cr_stripe') {
        $('#prod-option-' + create_stripe_buckle_type_id).change(function() {
            changeCrStripeColorOptions();
        });
    }
});

function handleNylonItemChange()
{
    if($('#prod-nylon-item').val() != 0) {
        url ='cb=' + Math.floor(Math.random()*99999999999) + '&size=' + $("#prod-detail-size").val() + '&prod_id=' + $("#prod-id").val();
        url += '&item=' + $('#prod-nylon-item').val();
        jQuery.ajax({
            url: '/ajax.php',
            type: 'GET',
            data: url,
            dataType: 'text',
            success: function(data) {
                
               $("#p-prod-price").html('');
               $('#prod_ind_price').val('');
               $("#prod-buckle-type").html('');
               $("#prod-nylon-buckle-color").html('');
               $('#prod-price-template-id').val('');
               $('.buckle_color_wrap').hide('fast', function() {});
                
                decoded = eval('(' + data + ')');
                $("#p-prod-price").html('');
                $('#prod_ind_price').val('');
                $("#prod-buckle-type").html('');
                $("#prod-nylon-buckle-color").html('');
                $('#prod-price-template-id').val('');
                
                if(decoded.nylon_buckle_type != undefined) {
                    $("#prod-buckle-type").html(decoded.nylon_buckle_type);
                    $('#prod-buckle-type').bind('change', handleNylonBklTypeChange);
                    $("#p-prod-price").html('');
                    $('#prod_ind_price').val('');
                    $('#prod-price-template-id').val('')
                }
                
                if(decoded.price != undefined && decoded.price_template != undefined) {
                    $('#prod-price-template-id').val(decoded.price_template);
                    if(!isNaN($('#qty').val())) {
                        $('#prod_ind_price').val(decoded.price);
                        decoded.price = truncate(parseFloat(decoded.price * $('#qty').val()));
                    }
                    
                    $('#p-prod-price').html('<label style="padding-top:5px;">Price: $' + decoded.price + '</label>');
                    // reset all the other dependent section html because its not needed
                    $("#prod-buckle-type").html('');
                    $("#prod-nylon-buckle-color").html('');
                }
                
                if(decoded.ws_temp_id != undefined) {
                    $('#prod-ws-price-template-id').val(decoded.ws_temp_id);
                }
                
                if(decoded.no_prod != undefined) {
                    $('#p-prod-price').html('<label style="padding-top:5px;">' + decoded.no_prod + '</label>');
                }
            }
        });
    } else {
       $("#p-prod-price").html('');
       $('#prod_ind_price').val('');
       $("#prod-buckle-type").html('');
       $("#prod-nylon-buckle-color").html('');
       $('#prod-price-template-id').val('');
       $('.buckle_color_wrap').hide('fast', function() {});
    }
}

function handleNylonBklTypeChange()
{
    if($('#prod-buckle-type').val() != 0) {
        url ='cb=' + Math.floor(Math.random()*99999999999) + '&size=' + $("#prod-detail-size").val() + '&prod_id=' + $("#prod-id").val();
        url += '&item=' + $('#prod-nylon-item').val() + '&bkl_type=' + $('#prod-buckle-type').val();
        jQuery.ajax({
            url: '/ajax.php',
            type: 'GET',
            data: url,
            dataType: 'text',
            success: function(data) {
                decoded = eval('(' + data + ')');
                if(decoded.nylon_buckle_color != undefined) {
                    $("#prod-nylon-buckle-color").html(decoded.nylon_buckle_color);
                    $("#prod-nylon-buckle-color").bind('change', handleNylonBklColorChange);
                    $("#p-prod-price").html('');
                    $('#prod_ind_price').val('');
                    $('#prod-price-template-id').val('');
                    // Add all the displayable colors
                    if(decoded.nylon_buckle_color_image != undefined) {
                        $(".buckle_color_wrap").html(decoded.nylon_buckle_color_image);
                        $(".buckle_color_wrap").show('slow', function() {});
                    }
                } else {
                    $('#prod-nylon-buckle-color').html('');
                }
                
                if(decoded.price != undefined && decoded.price_template != undefined) {
                    $('#prod-price-template-id').val(decoded.price_template);
                    
                    if(!isNaN($('#qty').val())) {
                        $('#prod_ind_price').val(decoded.price);
                        decoded.price = truncate(parseFloat(decoded.price * $('#qty').val()));
                    }
                    
                    $('#p-prod-price').html('<label style="padding-top:5px;">Price: $' + decoded.price + '</label>');
                    // reset all the other dependent section html because its not needed
                    $(".buckle_color_wrap").hide('slow', function() {});
                }
                
                if(decoded.ws_temp_id != undefined) {
                    $('#prod-ws-price-template-id').val(decoded.ws_temp_id);
                }
                
                if(decoded.no_prod != undefined) {
                    $('#p-prod-price').html('<label style="padding-top:5px;">' + decoded.no_prod + '</label>');
                }
                
                $("a.fancybox").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 500, 'zoomSpeedOut': 500 });
            }
        });
    } else {
       $("#p-prod-price").html('');
       $('#prod_ind_price').val('');
       $("#prod-nylon-buckle-color").html('');
       $(".buckle_color_wrap").html('');
       $('#prod-price-template-id').val('');
       $(".buckle_color_wrap").hide('slow', function() {});
    }
}

function handleNylonBklColorChange()
{
    if($('#prod-nylon-buckle-color').val() != 0) {
        url ='cb=' + Math.floor(Math.random()*99999999999) + '&size=' + $("#prod-detail-size").val() + '&prod_id=' + $("#prod-id").val();
        url += '&item=' + $('#prod-nylon-item').val() + '&bkl_type=' + $('#prod-buckle-type').val() + '&bkl_color=' + $('#prod-nylon-buckle-color').val();
        jQuery.ajax({
            url: '/ajax.php',
            type: 'GET',
            data: url,
            dataType: 'text',
            success: function(data) {
                decoded = eval('(' + data + ')');
                
                if(decoded.price != undefined && decoded.price_template != undefined) {
                    $('#prod-price-template-id').val(decoded.price_template);
                    
                    if(!isNaN($('#qty').val())) {
                        $('#prod_ind_price').val(decoded.price);
                        decoded.price = truncate(parseFloat(decoded.price * $('#qty').val()));;
                    }
                    
                    $('#p-prod-price').html('<label style="padding-top:5px;">Price: $' + decoded.price + '</label>');
                }
                
                if(decoded.ws_temp_id != undefined) {
                    $('#prod-ws-price-template-id').val(decoded.ws_temp_id);
                }
                
                if(decoded.no_prod != undefined) {
                    $('#p-prod-price').html('<label style="padding-top:5px;">' + decoded.no_prod + '</label>');
                }
                
                /*if(decoded.image != undefined) {
                    $('#img-buckle-color').attr('src', decoded.image);
                    $('#img-buckle-color').show('medium', function() {});
                }*/
            }
        });
    } else {
        $("#p-prod-price").html('');
        $('#prod_ind_price').val('');
        $('#prod-price-template-id').val('');
    }
}

function handleFabricBuckleTypeChange()
{
    if($('#prod-fabric-buckle-type').val() != 0) {
        url ='cb=' + Math.floor(Math.random()*99999999999) + '&size=' + $("#prod-detail-size").val() + '&prod_id=' + $("#prod-id").val();
        url += '&bkl_type=' + $('#prod-fabric-buckle-type').val();
        jQuery.ajax({
            url: '/ajax.php',
            type: 'GET',
            data: url,
            dataType: 'text',
            success: function(data) {
                decoded = eval('(' + data + ')');
                if(decoded.fabric_buckle_color != undefined) {
                    $("#prod-fabric-buckle-color").html(decoded.fabric_buckle_color);
                    $("#prod-fabric-buckle-color").bind('change', handleFabricBklColorChange);
                    if(decoded.fabric_buckle_color_images != undefined) {
                        $(".buckle_color_wrap").html(decoded.fabric_buckle_color_images);
                        $(".buckle_color_wrap").show('slow', function() {});
                    }
                    $("#p-prod-price").html('');
                    $('#prod_ind_price').val('');
                    $('#prod-price-template-id').val('');
                }
                
                $("a.fancybox").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 500, 'zoomSpeedOut': 500 });
            }
        });
    } else {
       $("#p-prod-price").html('');
       $('#prod_ind_price').val('');
       $(".buckle_color_wrap").hide('slow', function() {});
       $('#prod-price-template-id').val('');
       $("#prod-fabric-buckle-color").html('');
    }
}

function handleFabricBklColorChange()
{
    if($('#prod-fabric-buckle-color').val() != 0) {
        url ='cb=' + Math.floor(Math.random()*99999999999) + '&size=' + $("#prod-detail-size").val() + '&prod_id=' + $("#prod-id").val();
        url += '&bkl_type=' + $('#prod-fabric-buckle-type').val() + '&bkl_color=' + $('#prod-fabric-buckle-color').val();
        jQuery.ajax({
            url: '/ajax.php',
            type: 'GET',
            data: url,
            dataType: 'text',
            success: function(data) {
                decoded = eval('(' + data + ')');
                if(decoded.price != undefined && decoded.price_template != undefined) {
                    $('#prod-price-template-id').val(decoded.price_template);
                    if(!isNaN($('#qty').val())) {
                        $('#prod_ind_price').val(decoded.price);
                        decoded.price = truncate(parseFloat(decoded.price * $('#qty').val()));;
                    }
                    $('#p-prod-price').html('<label style="padding-top:5px;">Price: $' + decoded.price + '</label>');
                    
                }
                
                if(decoded.ws_temp_id != undefined) {
                    $('#prod-ws-price-template-id').val(decoded.ws_temp_id);
                }
            }
        });
    } else {
       $("#p-prod-price").html('');
       $('#prod_ind_price').val('');
       $('#prod-price-template-id').val('');
       $('#img-buckle-color').hide('fast', function() {});
    }
}

// Add daisy pop size changes and the character limitations
function handleDaisyPopTagSizeChange()
{
    var size_text = $('#prod-option-' + daisy_pop_size + ' :selected').text();
    if(size_text.indexOf('Large') != -1) {
        $('#prod-option-' + daisy_pop_shape).append(daisy_pop_paw_cut);
    } else {
        $("#prod-option-" + daisy_pop_shape + " option[value='" + daisy_pop_paw_cut_val_id + "']").remove();
    }
    
    // Add max length attribute to the engraving front and back fields
    var eng_front_max;
    var eng_back_max;

    if(size_text.indexOf('Tiny') != -1 || size_text.indexOf('Small') != -1) {
        eng_front_max = 12;
        eng_back_max = 13;
    }
    if(size_text.indexOf('Large') != -1 || size_text.indexOf('XL') != -1 || size_text.indexOf('Super') != -1) {
        eng_front_max = 16;
        eng_back_max = 27;
    }

    $('#prod-option-' + daisy_pop_eng_front).attr('maxlength', eng_front_max);
    $('#prod-option-' + daisy_pop_eng_back).attr('maxlength', eng_back_max);
}

function handleRedDingoDogTagDesignChange()
{
    var selected_text = $('#prod-option-' + red_dingo_dog_tag_design + ' :selected').text();
    var no_color = false;
    
    switch(selected_text) {
        case 'Australian Flag 1AU':
        case 'Black & Red Heart 1HB':
        case 'Blue Butterfly 1BL':
        case 'Clover 1CV':
        case 'Pink Butterfly 1BP':
        case 'Pink Heart 1HK':
        case 'Purple Heart 1HP':
        case 'Red Cross 1SC':
        case 'Soccer Ball 1SB':
        case 'Snowflake 1SF':
        case 'Stars & Stripes 1US':
        case 'Tribal Sun 1TS':
        case 'UK Flag 1UK':
        case 'Ying & Yang 1YY':
            no_color = true;
            break;
        default:
            break;
    } 
    
    if(no_color) {
        $('#prod-option-' + red_dingo_dog_tag_color).prepend('<option value="000">As Shown</option>');
        $('#prod-option-' + red_dingo_dog_tag_color).attr('disabled', true);
        $('#prod-option-' + red_dingo_dog_tag_color + ' option:first').attr('selected','selected');
    } else {
        $('#prod-option-' + red_dingo_dog_tag_color).attr('disabled', false);
        $("#prod-option-" + red_dingo_dog_tag_color + " option[value='000']").remove();
    }
    //  $('#prod-option-' + red_dingo_dog_tag_color)
}

function changeCrStripeColorOptions()
{
    if($('#prod-option-' + create_stripe_buckle_type_id).val() == '') {
        $('#buckle_color_image_div').html('');
        $('#prod-option-' + create_stripe_buckle_color_id).html('<option value="">Select Buckle Color</option>');
    } else {
        if($('#prod-option-' + create_stripe_buckle_type_id + ' :selected').text().indexOf('Plastic') != -1) {
            $('#prod-option-' + create_stripe_buckle_color_id).html('<option value="">Select Buckle Color</option>' + bkl_col_opt_plastic);
            $('#prod-option-' + create_stripe_buckle_color_id).attr('disabled', false);
            $('#buckle_color_image_div').html(bkl_col_color_plastic);
            $("a.fancybox").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 500, 'zoomSpeedOut': 500 });
        }
        
        if($('#prod-option-' + create_stripe_buckle_type_id + ' :selected').text().indexOf('Metal') != -1) {
            $('#prod-option-' + create_stripe_buckle_color_id).html('<option value="">Select Buckle Color</option>' + bkl_col_opt_metal);
            $('#prod-option-' + create_stripe_buckle_color_id).attr('disabled', false);
            $('#buckle_color_image_div').html(bkl_col_color_metal);
            $("a.fancybox").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 500, 'zoomSpeedOut': 500 });
        }
        
        if($('#prod-option-' + create_stripe_buckle_type_id + ' :selected').text().indexOf('Plastic') == -1 && $('#prod-option-' + create_stripe_buckle_type_id + ' :selected').text().indexOf('Metal') == -1) {
            $('#prod-option-' + create_stripe_buckle_color_id).attr('disabled', true);
            $('#buckle_color_image_div').html('');
        }
    }
}

function truncate(num) { 
    string = "" + num; 
    if(string.indexOf('.') == -1) 
        return string + '.00'; 
    seperation = string.length - string.indexOf('.'); 
    if(seperation > 3) 
        return parseFloat(string.substring(0,string.length-seperation+3)).toFixed(2); 
    else if(seperation == 2) 
        return string + '0'; 
    return string; 
}
