var ajaxurl = '/wp-admin/admin-ajax.php';
var $j = jQuery.noConflict();

$j(document).ready(function(){
    var $ = jQuery.noConflict();
    // Hide unecessary user profile stuff.
    var hideFields = [ "description", "url", "rich_editing", "admin_color_classic", "comment_shortcuts", "admin_bar_front", "display_name", "nickname"];
    $.each( $( "form#your-profile tr" ), function() {
        var field = jQuery( this ).find( "input,textarea,select" ).attr( "id" );
        if ( hideFields.indexOf( field ) != -1 ) {
            jQuery( this ).remove();
        }
    });
    $("h3:contains('Personal Options')").remove();



    $('.cart-remove').live('click',function() {
        var product = $(this);
        var item = product.parents('.order-item').attr('id').toString();

        var data = {
            action: 'dcc_update_cart',
            id: item,
            quantity: 0
        };
        
        $.post(ajaxurl, data, function(r) {
                product.parents('.order-item').slideUp('slow');
                
                
                $('#order-total h2').html(r.subTotal);
                $('#order-summary-subtotal').html(r.subTotal);
                
                var itemCount = r['totalQty'] + ' Item';
                if (r['totalQty'] != 1)
                    itemCount += 's';
                $('ul#top-links li.cart a').html(itemCount);
                $('div#footer .cart').html(itemCount);
                
        }, 'json');
        
        return false;
        
    });
    
    $('.update-button').live('click',function() {

        var button = $(this);
        var item = button.parents('.order-item').attr('id').toString();
        var quantity = button.siblings('.update-value');

        if (validate_qty(quantity, quantity.attr('name'))) {
            var qty = quantity.val();
            quantity.attr('name', qty);

            var data = {
                action: 'dcc_update_cart',
                id: item,
                quantity: qty
            };

            var angle = 0;
            angle+=5;
            button.rotate(angle);
            var rotateInt = setInterval(function(){
                angle+=5;
                button.rotate(angle);
            }, 5);

            $.post(ajaxurl, data, function(r) {
                    //product.parents('.order-item').slideUp('fast');
                clearInterval(rotateInt);

                button.parents('.order-item').find('.cart-price h1').html(r.price);
                
                $('#order-total h2').html(r.subTotal);
                $('#order-summary-subtotal').html('$' + r.subTotal);
                
                
                var itemCount = r['totalQty'] + ' Item';
                if (r['totalQty'] != 1)
                    itemCount += 's';
                $('ul#top-links li.cart a').html(itemCount);
                $('div#footer .cart').html(itemCount);
                
                if(qty<1){
                    button.parents('.order-item').slideUp('slow');
                }

            }, 'json');
        }
        return false;
        
    });
    
    /*
    $('.buy-btn .buy-button').live('click',function(){
        //$(this).children('.buy-quantity');
        
        var quantity = $(this).parent().find('.buy-quantity')[0];
        validate_qty($(quantity), $(this).attr('id').toString().split('-')[1]);
        var qty = $(quantity).val();
        var item = $(this).attr('id').toString().split('-')[1];

        if (!isNaN(qty) && qty > 0 && item) {
            alert('Item: ' + item + ' - Quantity: ' + qty);
            var data = {
                action: 'dcc_add_to_cart',
                id: item,
                quantity: qty
            };
            alert(ajaxurl);
            $.post(ajaxurl, data, function(r) {
                var itemCount = r['totalQty'] + ' Item';
                if (r['totalQty'] != 1)
                    itemCount += 's';
                $('ul#top-links li.cart a').html(itemCount);
                $('div#footer .cart').html(itemCount);
                
              }, 'json');
        }
        else if (!item) {
            $('.popup-info-sizes>ul').css({
                backgroundColor: '#f00'
            }).animate({
                backgroundColor: '#fff'
            }, 300);
        } else {
            $('#popup-input-qty').css({
                border: 'solid 1px #f00',
                backgroundColor: '#f00'
            }).animate({
                border: '1px solid #DBDBDB',
                backgroundColor: '#fff'
            }, 300);
        }
        $('a#btn-addcart').blur();


        return false;
    });*/
    
     $('#replace-order').live('click',function(){

        //var quantity = $(this).parent().find('.buy-quantity')[0];
        //validate_qty($(quantity), $(this).attr('id').toString().split('-')[1]);
        
        var order_id = $(this).attr('href');
        var data = {
                action: 'dcc_replace_order',
                id: order_id
            };
         $.post(ajaxurl, data, function(r) {
             console.log('Placed');
             if (r['message'])
                alert(r['message']);
             var itemCount = r['outcome']['totalQty'] + ' Item';
            if (r['outcome']['totalQty'] != 1)
                itemCount += 's';
            $('ul#top-links li.cart a').html(itemCount);
            $('div#footer .cart').html(itemCount);
         }, 'json');
        //alert("ok");
        return false;
    });
    
    $('.buy-btn .buy-button').live('click',function(){
        //$(this).children('.buy-quantity');
        
        var quantity = $(this).parent().find('.buy-quantity')[0];
        validate_qty($(quantity), $(this).attr('id').toString().split('-')[1]);
        
        return false;
    });

    function validate_qty(quantity, item, orig){
        
        if (!orig)
            orig = '0';
        
        if (isNaN(quantity.val()) || !quantity.val()) {
            quantity.val(orig);
            quantity.attr('name', orig);
            return false;
        }

        var item_id = item.split('_')[0];
        var variation_id = item.split('_')[1]

        var data = {
                action: 'dcc_get_product_stock',
                item_id: item_id,
                variation_id: variation_id,
                quantity: quantity.val()
            };
            //alert('Quan:' + quantity.val());
        $.post(ajaxurl, data, function(r) {
            var remaining = r['remaining'];

            if (parseInt(remaining) < parseInt(quantity.val())) {
                alert("We’re sorry, we don’t have enough stock to fill that order. There are currently " + remaining + " left.")
                quantity.val(orig);
                quantity.attr('name', orig);
                return false;
            }
            else {
                var qty = $(quantity).val();

                if (!isNaN(qty) && qty > 0 && item) {
                    //alert('Item: ' + item + ' - Quantity: ' + qty);
                    var data = {
                        action: 'dcc_add_to_cart',
                        id: item,
                        quantity: qty
                    };
                    //alert(ajaxurl);
                    $.post(ajaxurl, data, function(r) {
                        var itemCount = r['totalQty'] + ' Item';
                        if (r['totalQty'] != 1)
                            itemCount += 's';
                        $('ul#top-links li.cart a').html(itemCount);
                        $('div#footer .cart').html(itemCount);
                        confirm();

                      }, 'json');
                }
                
                return false;
            }
          }, 'json');
        
        return true;

    }
  function confirm(){
    $.fancybox('<h2>Added To Cart</h2><p>Your item(s) have been successfully added to your cart.</p><p><a href="/cart">Go to Cart</a></p>');
    
    $('#fancybox-outer').css('background-color','#181818');
    $('#fancybox-content').css('padding','5px');
    
    $('#fancybox-outer').addClass('fancybox-modal-outer');
    $('#fancybox-content').addClass('fancybox-modal-content');
    
    setTimeout(function(){
      $.fancybox.close();
    },5000);
  }

  $('#ship_name')  .watermark('<i>Name</i>');
  $('#bill_line1,  #ship_line1')  .watermark('<i>Address Line 1</i>');
  $('#bill_line2,  #ship_line2')  .watermark('<i>Address Line 2</i>');
  $('#bill_city,   #ship_city')   .watermark('<i>City</i>');
  $('#bill_prov,   #ship_prov')   .watermark('<i>Province</i>');
  $('#bill_post,   #ship_post')   .watermark('<i>Postal Code</i>');
  $('#bill_country,#ship_country').watermark('<i>Country</i>');
  if($('#email').css('display') != 'none'){
  $('#email')                     .watermark('<i>Email</i>');
  }
  $('#fullname')                  .watermark('<i>Full Name</i>');
  $('#phone')                     .watermark('<i>Phone</i>');
  
  $('#cc_firstname').watermark('<i>First Name</i>');
  $('#cc_lastname').watermark('<i>Last Name</i>');
  $('#cc_number').watermark('<i>Credit Card Number</i>');
  $('#cc_type').watermark('<i>Type</i>');
  $('#cc_cvv2').watermark('<i>CVV2</i>');
  $('#cc_month').watermark('<i>Month</i>');
  $('#cc_year').watermark('<i>Year</i>');
  $('#cc_name').watermark('<i>Name</i>');
  
  /**
   * Checkout Billing/Shipping Copy
   */
  $('div#apply>input[type=checkbox]').click(function(){
    if($(this).is(':checked')){
      var transitionClass = 'address-effects-transfer';
      var timing = 500;
      var afterColor = '#8A8A8A';
      transitionValue('#bill_line1',  '#ship_line1',   transitionClass, timing, afterColor, false);
      transitionValue('#bill_line2',  '#ship_line2',   transitionClass, timing, afterColor, false);
      transitionValue('#bill_city',   '#ship_city',    transitionClass, timing, afterColor, false);
      transitionValue('#bill_country','#ship_country', transitionClass, timing, '#000'    , true);
      
    if ($('#bill_prov_us').attr('name') != 'nosubmit') 
        transitionValue('#bill_prov_us',   '#ship_prov_us',    transitionClass, timing, '#000'    , true);
    else if ($('#bill_prov_canada').attr('name') != 'nosubmit') 
        transitionValue('#bill_prov_canada',   '#ship_prov_canada',    transitionClass, timing, '#000'    , true);
    else if ($('#sbill_prov_other').attr('name') != 'nosubmit') {
        transitionValue('#bill_prov_other',   '#ship_prov_other',    transitionClass, timing, '#000'    , true);
        transitionValue('#bill_prov_txt',   '#ship_prov_txt',    transitionClass, timing, '#000'    , true);
    }
      
      transitionValue('#bill_post',   '#ship_post',    transitionClass, timing, afterColor, false);
    }
  });
  
  function transitionValue(s1, s2, THEclass, timing, afterColor, checkStateOnCallback){
    $(s2).animate({color:'#fff'},timing);
    var FadeInPrev=false;
    if(!$(s2).val()){
      $(s2).prev().fadeOut(timing);
      FadeInPrev=true;
    }
    $(s1).effect('transfer', {to: s2, className: THEclass}, timing, function(){
      $(s2).val($(s1).val()).animate({color:afterColor},timing);
      if(FadeInPrev){
        $(s2).prev().fadeIn(timing);
        $(s2).focus();
      }
      if(checkStateOnCallback){
        evaluateStates();
      }
    });
  }
  
  
  /**
   * Checkout Button
   */
  
    $('.checkout-btn').click(function(){
        
        var loggedin = $('#is_user_loggedin').val();
        if(loggedin=='true'){
          doCheckout();
          return false;
        }else{
          var data = '';

          $('#checkout-form input').each(function(){
            if($(this).attr('type')=='text' || $(this).attr('type')=='hidden'){
              data += $(this).attr('name') + '=' + $(this).val() + '&';
              //alert($(this).attr('name') + '=' + $(this).val());
            }
            if($(this).attr('type')=='checkbox' && $(this).is(':checked')){
              data += $(this).attr('name') + '=' + $(this).val() + '&';
              //alert($(this).attr('name') + '=' + $(this).val());
            }
          });

          data += 'action=dcc_create_account_popup';

          $.post(ajaxurl,data,function(r){
            $.fancybox(r, {'width': 810,
                'autoScale'         :  false,
                'autoDimensions'    : true,
                'transitionIn'      : 'fade',
                'transitionOut'     : 'fade',
                'speedIn'           : 500,
                'speedOut'          : 200,
                'padding'           : 0
                });
                
            $('#fancybox-outer').addClass('fancybox-modal-outer');
            $('#fancybox-content').addClass('fancybox-modal-content');
          });
          return false;
        }
  });
  
  function doCheckout(){
/*
    $.fancybox('<div id="product-popup">Please wait while your order is processed</div>', {'width': 810,
            'autoScale'         :  false,
            'autoDimensions'    : true,
            'transitionIn'      : 'fade',
            'transitionOut'     : 'fade',
            'speedIn'           : 500,
            'speedOut'          : 200,
            'padding'           : 0
            });
*/
    // Check the stock.
    var info = 'action=dcc_check_stock';
    $.post(ajaxurl, info, function(r){
        if (r['success']) {
            
            var data = collect_form_data();
            data += 'action=dcc_process_cc';
            $.post(ajaxurl, data, function(d){
      
                $.fancybox(d.message, {'width': 810,
                    'autoScale'         :  false,
                    'autoDimensions'    : true,
                    'transitionIn'      : 'fade',
                    'transitionOut'     : 'fade',
                    'speedIn'           : 500,
                    'speedOut'          : 200,
                    'padding'           : 0
                    });

                $('#fancybox-outer').addClass('fancybox-modal-outer');
                $('#fancybox-content').addClass('fancybox-modal-content');

                if (d.valid) {
                    window.location.replace('/success?amount=' + d.amount
                                            + '&transactionId=' + d.transactionId 
                                            + '&authCode=' + d.authCode
                                            + '&date=' + d.date
                                            + '&message=' + d.message);
                }
      
            },'json');
        }
        else {
            $.fancybox('<div id="product-popup">' + r['message'] + '</div>', {
                'autoDimensions'	: false,
                'width'         		: 350,
                'height'        		: 'auto',
                'transitionIn'		: 'none',
                'transitionOut'		: 'none'
                });
        }
    }, 'json');
    
    // OLD WAY
    /*
    $.post(ajaxurl,data,function(r){
      /*$('#product-blackout, #product-popup').remove();
      $('body').append('<div id="product-blackout">&nbsp;</div>');
      $('body').append('<div id="product-popup">&nbsp;</div>');
      $('div#product-blackout').css('top',$(window).scrollTop()+'px');
      //open_popup();
      $('#product-popup').html(r.message);
      *//*
      $.fancybox(r.message, {'width': 810,
            'autoScale'         :  false,
            'autoDimensions'    : true,
            'transitionIn'      : 'fade',
            'transitionOut'     : 'fade',
            'speedIn'           : 500,
            'speedOut'          : 200,
            'padding'           : 0
            });
            
      if (r.valid) {
          window.location.replace('/success?amount=' + r.amount
                                    + '&transactionId=' + r.transactionId 
                                    + '&authCode=' + r.authCode
                                    + '&date=' + r.date
                                    + '&message=' + r.message);
      }
      
    },'json');*/
  }
 
  /**
   * Create Account Pop-up Functions
   */
  $('#createAccount').live('click', function(){
    validateAccountCreation(true);
    return false;
  });
  
  function validateAccountCreation(saveData){
    
    var data = collect_form_data();
    
    if(saveData){
      data += 'savemeta=true&';
    }
    
    data += 'action=dcc_validate_and_create_user';
    
    $.post(ajaxurl,data,function(r){
      if(r.valid){
        var html = $('#account-popup-user-actions').html();
        html = r.message;
        $('#account-popup-user-actions').html(html);
      }else{
        var html = $('#account-popup-user-actions').html();
        html = r.message + '<br />' + html;
        $('#account-popup-user-actions').html(html);
      }
    },'json');
  }
  
  $('#created-account-process-order').live('click',function(){
    doCheckout();
    return false;
  });
  
  $('#skipAccount').live('click',function(){
    doCheckout();
    return false;
  });
  
  function collect_form_data(selectValue){
    var data = '';
    $('#checkout-form input').each(function(){
      if($(this).attr('type')=='text'  || $(this).attr('type')=='hidden'){
        if($(this).attr('name')){
          data += $(this).attr('name') + '=' + encodeURIComponent($(this).val()) + '&';
        }
      }
      if($(this).attr('type')=='checkbox' && $(this).is(':checked')){
        if($(this).attr('name')){
          data += $(this).attr('name') + '=' + $(this).val() + '&';
        }
      }
    });
    $('#checkout-form select').each(function(){
      if($(this).attr('name')){
        if(selectValue=='html'){
          data += $(this).attr('name') + '=' + encodeURIComponent($('option:selected',this).html()) + '&';
        }else{
          data += $(this).attr('name') + '=' + encodeURIComponent($(this).val()) + '&';
        }
      }
    });
    return data;
  }
  
  /**
   * State/Provice List
   */
  $('#ship_country, #bill_country, .ship_prov_selector').change(function(){
      evaluateStates();
  });
  evaluateStates();
  function evaluateStates() {
      if($('#ship_country').val()=='CA'){
      $('#ship_prov_canada').show();
      $('#ship_prov_us').hide();
      $('#ship_prov_other').hide();
      
      $('#ship_prov_canada').attr('name', 'ship_prov');
      $('#ship_prov_us').attr('name', 'nosubmit');
      $('#ship_prov_other').attr('name', 'nosubmit');
      
      $('#ship_prov_txt').hide();
      
      changePrice('#ship_prov_canada');
    }else if($('#ship_country').val()=='US'){
      $('#ship_prov_canada').hide();
      $('#ship_prov_us').show();
      $('#ship_prov_other').hide();
      
      $('#ship_prov_canada').attr('name', 'nosubmit');
      $('#ship_prov_us').attr('name', 'ship_prov');
      $('#ship_prov_other').attr('name', 'nosubmit');
      
      $('#ship_prov_txt').hide();
      changePrice('#ship_prov_us');
    }else{
      $('#ship_prov_canada').hide();
      $('#ship_prov_us').hide();
      $('#ship_prov_other').show();
      
      $('#ship_prov_canada').attr('name', 'nosubmit');
      $('#ship_prov_us').attr('name', 'nosubmit');
      $('#ship_prov_other').attr('name', 'ship_prov');
      
      $('#ship_prov_txt').show();
      changePrice('#ship_prov_other');
    }

    if($('#bill_country').val()=='CA'){
      $('#bill_prov_canada').show();
      $('#bill_prov_us').hide();
      $('#bill_prov_other').hide();
      
      $('#bill_prov_canada').attr('name', 'bill_prov');
      $('#bill_prov_us').attr('name', 'nosubmit');
      $('#bill_prov_other').attr('name', 'nosubmit');
      
      $('#bill_prov_txt').hide();
    }else if($('#bill_country').val()=='US'){
        
      $('#bill_prov_canada').hide();
      $('#bill_prov_us').show();
      $('#bill_prov_other').hide();
      
      $('#bill_prov_canada').attr('name', 'nosubmit');
      $('#bill_prov_us').attr('name', 'bill_prov');
      $('#bill_prov_other').attr('name', 'nosubmit');
      
      $('#bill_prov_txt').hide();
    }else{
      $('#bill_prov_canada').hide();
      $('#bill_prov_us').hide();
      $('#bill_prov_other').show();
      
      $('#bill_prov_canada').attr('name', 'nosubmit');
      $('#bill_prov_us').attr('name', 'nosubmit');
      $('#bill_prov_other').attr('name', 'bill_prov');
      
      $('#bill_prov_txt').show();
    }
  }
  
  function changePrice(province) {
      var prov = $(province).val();
        var country = $('#ship_country').val();

        var data = {
                action: 'dcc_calculate_shipping',
                prov: prov,
                country: country
            };
            
            $.post(ajaxurl, data, function(r) {
                if (r) {
                    if (r['shipping_message']) {
                        $('#order-summary-shipping').html(r['shipping_message']);
                    }
                    else {
                        $('#order-summary-shipping').html('$' + r['shipping']);
                    }
                    $('#order-summary-subtotal').html('$' + r['subtotal']);
                    $('#order-summary-grandtotal').html('$' + r['grandtotal']);
                    $('#order-summary-tax').html('$' + r['tax']);
                }
              }, 'json');
  }
  
    $('#apply-coupon-button').click(function() {
        var couponCode = $('#coupon-code-box').val();
        var country = $('#ship_country').val();
        
        if (couponCode) {
            var data = {
                action: 'dcc_apply_coupon_code',
                code: couponCode,
                country: country
            };

            $.post(ajaxurl, data, function(r) {
                if (r['success']) {
                    $('#order-summary-subtotal').html('$' + r['subtotal']);
                    $('#order-summary-grandtotal').html('$' + r['grandtotal']);
                    $('#order-summary-tax').html('$' + r['tax']);
                    $("#coupon-code-message").html(r['message']);
                    $("#coupon-code-message").fadeIn();
                }
                else {
                    $("#coupon-code-message").html(r['message']);
                    $("#coupon-code-message").fadeIn();
                }

                //alert(r);
                /*
                for (i = 0; i < r.length; i++) {
                   // alert('Country: ' + r[i]['country'] + ' Province: ' + r[i]['province'] + ' Cost: ' + r[i]['cost']);
                   alert(r[i]);
                }*/
                //alert("NOPE");
                //var itemCount = r['totalQty'] + ' Item';
                //if (r['totalQty'] != 1)
                //    itemCount += 's';
          }, 'json');
      }
      return false;
  });

  function selectTheFirstVisibleOptionIfTheCurrentlySelectedOptionIsNotVisible(selector){
    if($(selector+'>option:selected').is(':visible')){
    }else{
      $(selector+'>option:selected').removeAttr('selected');
      var first = true;
      $(selector+'>option:visible').each(function(){
        if(first){
          $(this).attr('selected','selected');
          evaluateStates();
        }
        first=false;
      });
    }
  }
  
  /**
   * Blurring
   */
  $('#popup-box a').live('click',function(){
    $(this).blur();
  });
  
  /**
   * Login Link
   */
  $('.login-link').live('click', function(){

    var data = {
      action: 'dcc_login_window'
    };
    
    $.post(ajaxurl,data,function(r){
      $('body').append(r);
      $('div#product-blackout').css('top',$(window).scrollTop()+'px');
      open_popup();
    });
    
    return false;
  });
  $('#do-login').live('click',function(){
    
    
    var data = {
      action: 'dcc_do_login',
      username: $('#username').val(),
      password: $('#password').val()
    };
    
    $.post(ajaxurl,data,function(r){
      $('div#product-blackout, div#product-popup').remove();
      $('body').append(r);
      $('div#product-blackout').css('top',$(window).scrollTop()+'px');
      
      open_popup();
    });
    
    return false;
  });
  
  /**
   * Close add to cart message box
   */
  $('#item-added-to-cart-message').live('click', function(){
    $(this).fadeOut(500, function(){
      $(this).remove();
    });
  });
  
  // Handle tabs on product details page.
  $('#product-info .product-tabs>li>a').live('click', function() {
      // Change tab state when clicked.
      var tabs = $('#product-info .product-tabs>li');
      tabs.each(function() {
         $(this).attr('class', ''); 
      });
      $(this).parent().addClass('active');
      
      // Display the correct data for the tab that was clicked.
      $('#product-info>div').each(function() {
          $(this).hide();
      });
      var paragraph = $(this).attr('href').toString();
      $(paragraph).stop().fadeIn('fast');

      return false;
  })
  
  $('.newsletter').parent().addClass('news-signup');
  
  
  
    $('#shipping-same-as-billing').click(function(){
        if($(this).is(':checked')){
            var transitionClass = 'address-effects-transfer';
            var timing = 500;
            var afterColor = '#8A8A8A';
            transitionValue('#bill_line1',        '#ship_line1',    transitionClass, timing, afterColor, false);
            transitionValue('#bill_line2',        '#ship_line2',    transitionClass, timing, afterColor, false);
            transitionValue('#bill_city',         '#ship_city',     transitionClass, timing, afterColor, false);
            transitionValue('#bill_prov_txt',     '#ship_prov_txt', transitionClass, timing, afterColor, false);
            transitionValue('#bill_country',      '#ship_country',  transitionClass, timing, '#000'    , true);

            if ($('#bill_prov_us').attr('name') != 'nosubmit') 
                transitionValue('#bill_prov_us',   '#ship_prov_us',    transitionClass, timing, '#000'    , true);
            else if ($('#bill_prov_canada').attr('name') != 'nosubmit') 
                transitionValue('#bill_prov_canada',   '#ship_prov_canada',    transitionClass, timing, '#000'    , true);
            else if ($('#bill_prov_other').attr('name') != 'nosubmit') 
                transitionValue('#bill_prov_other',   '#ship_prov_other',    transitionClass, timing, '#000'    , true);

            transitionValue('#bill_post',   '#ship_post',    transitionClass, timing, afterColor, false);
        }
    });
  
});
