/*===============ToolBar Clean up=================================*/

$(function(){
    $('#search-form label').hide();
    var text = $('#search-form label').text();
    $('#search-form label').before('<div id="searchIcon"></div>');

    function defaultSearchText(){
        $('#search-form #searchterms').addClass('greyedout').attr('value', text);
    }
    defaultSearchText();

    $('#search-form #searchterms').focus(function(){
        if($(this).attr('value') == text){
            $(this).removeClass('greyedout').attr('value', '');
        }
    });
    $('#search-form #searchterms').blur(function(){
        if($(this).attr('value') == ''){
            defaultSearchText();
        }
    });

    $('#login').click(function(e){
        e.preventDefault();
        $('.modal').modal({
            closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>"
        });
    });
    
/*===============Home Slideshow=================================*/

    $('#home-slideshow').cycle({
        fx:     'fade',
        speed:  'fast',
        timeout: 3000,
        pager:  '#slide-nav',
        pagerAnchorBuilder: function(idx, slide) {
            // return selector string for existing anchor
            return '#slide-nav li:eq(' + idx + ') a';
        }
    });

});

/*=========================Ajax Cart ==============================*/ /*  http://eli.twstest.internal//cart.php?__formAction=getJsonCart  */

$(function(){
    $.ajax({
          url: '/cart.php?__formAction=getJsonCart',
          dataType: 'json',
          data: false,
          success: function(data){
              updateCartWidget(data);
            }
    });
});

$('#view-cart-widget').live('click', function(e){
    // e.preventDefault();
    getCartContents();

})
$('.delete-item a').live('click', function(e){
    e.preventDefault();
    var rawid = $(this).attr('id');
    ajaxRemoveItem(rawid);
})
//$('.pricing-options span#add-to-ajax').live('click', function(){
//    var id = $(this).parents('select').val();
//    if(!id){
//        id = $('input.add-to-cart',this).attr('id').replace('buyBtn_', '');
//    }
//    ajaxAddItem(id);
//})
// $('input.add-to-cart').live('click', function(e){
//     e.preventDefault();
// });
// 
$('#pop-update').live('click', function(e){
    e.preventDefault();
    var data = "quantity_0=0";
    $('#pop-cart form input[type="text"]').each(function(){
        data += '&quantity_'+$(this).attr('id')+'='+$(this).val();
    })
    ajaxUpdateQty(data);
})

function getCartContents(){
  $.ajax({
      url: '/cart.php?__formAction=getJsonCart',
      dataType: 'json',//text
      data: false,
      success: function(data){
          // showCart(data);
        }
    });
}

function ajaxUpdateQty(data){
    $.ajax({
          url: '/cart.php?__formAction=saveShoppingCart',
          dataType: 'json',
          data: data,
          type: "POST",
          success: function(r_data){
              showCart(r_data);
          }
    });
}

function ajaxAddItem(id){
    $.ajax({
          url: '/cart.php?__formAction=showShoppingCart',
          dataType: 'text',
          data: {itemid: id},
          success: getCartContents
          
    });
}
// 
// function ajaxRemoveItem(id){
//     var data = {};
//     data[id] = 1;
// 
//     $.ajax({
//           url: '/cart.php?__formAction=showShoppingCart',
//           dataType: 'text',
//           data: data,
//           type: "POST",
//           success: getCartContents
// 
//     });
// }
// 
// function showCart(data){
//     updateCartWidget(data);
//     var htmlBlock = "";
//     var total = 0;
//     for ( var i in data )
//     {
//         lineTotal = data[i].cartqty*data[i].price;
//         htmlBlock += '<tr><td class="pop-title">'+data[i].name+' </td>\n\
//                         <td class="pop-price">$'+data[i].price+'</td>\n\
//                         <td class="fixed-qty">x <input type="text" id="'+data[i].numericid+'" name="name" value="'+data[i].cartqty+'" /></td>\n\
//                         <td class="pop-line-total">$'+lineTotal.toFixed(2)+'</td>\n\
//                         <td class="delete-item"><a title="Remove from Cart" id="remove_'+data[i].numericid+'"href="">'+data[i].numericid+'</a></td></tr>';
// 
//         total += parseFloat(lineTotal);
//     }
//     total = Math.round(total*100)/100
// 
//     $('#pop-cart table').html(htmlBlock);
//     $('#pop-cart #pop-total').html('$'+total.toFixed(2));
// 
//     $('#pop-cart').modal({
//         opacity:30,
//         closeClass: "modalClose",
//         overlayClose:true
//     });
//     
// }
function updateCartWidget(data){
    var widgetBlock = "";
    var lineName = "";
    var total = 0;
    for ( var i in data )
    {
        lineTotal = data[i].cartqty*data[i].price;
        tempName = data[i].name;
        if(tempName.length > 25){
        lineName = tempName.substring(0,23)+'...';
        }else{lineName = tempName}
        widgetBlock += '<li>'+lineName+' </li>';

        total += parseFloat(lineTotal);
    }
    total = Math.round(total*100)/100

    if(data == ''){
        $('#cart-widget ul').html('<li>Your Cart is empty</li>');
        $('#widget-controls').hide();

    }else{
        $('#widget-controls').show();
        $('#cart-widget ul').html(widgetBlock);
        $('#total-widget span').html('$'+total.toFixed(2));
    }

}
/*=========================Change Add to cart button when using drop down, also change Price==============================*/ 
$(function(){
	//When you change the options on a product drop down...
	$(".pricing-options select").change(function () {
    var str = "";
		var currItem = "";
		//Save the Default price.
		var currPrice = $(this).siblings('.price-val').attr('name');
		var price = 0;
		//Get the ID of the Div enclosing this select list, incase of multiples on a page.
		var master = $(this).parents('div').attr('id');
		//Use the selected option
        $("select option:selected").each(function () {
			//Price String $00.00)
			var example = /\$(\d+.\d+)\)/;
			//Positive
			var pos = /\+ \$/;
			//Negative
			var neg = /\- \$/;
            str = $(this).attr('class');
			currItem = $(this).val();
			var preprice = $(this).text();
			//Grab the price difference, if any.
			var preprice2 = example.exec(preprice);
			if(str == "discontinued"){
				price = "Item is no longer in production"
			}else{
				var pre = 0;
				if(preprice2){
					//If the price is positive, add if it is negative, subtract
					if(pos.test(preprice)){
						pre = Math.round((parseFloat(preprice2[1]) + parseFloat(currPrice))*100)/100;
					}else if(neg.test(preprice)){
						pre = Math.round((parseFloat(preprice2[1]) - parseFloat(currPrice))*100)/100;
					}
				}else{
					pre = currPrice;
				}
				price = '$'+pre;
			}
		switch(str)
		{
		case "soldout":
			if($('#'+master+' .no-buy')){
				$('#'+master+' .no-buy').hide();
			}
			$('#'+master+' #add-to-ajax').html('').hide();
			$('#'+master+' #add-to-ajax').after('<div class="out-of-stock-btn no-buy">\
			   <!-- [blk.soldout;if [val]=1;then "soldout";else "";magnet=div] -->\
			   <p>OUT OF STOCK</p><a id="'+currItem+'" class="notify-me" title="Be alerted as soon as this is available" style="font-size: 9pt;"  \
			   href="/notifyme.php?item='+currItem+'&amp;type=itemrestock" target="notify_'+currItem+'"></a>\
			   </div>');
		    $('#'+master+' strong').show();  
		 break;
		case "preorder":
			if($('#'+master+' .no-buy')){
				$('#'+master+' .no-buy').hide();
			}
		  	$('#'+master+' #add-to-ajax').html('').hide();
			$('#'+master+' #add-to-ajax').after('<div class="coming-soon-btn no-buy">\
			<!-- [blk.preorder;if [val]=1;then "soldout";else "";magnet=div] -->\
			<p>COMING SOON!</p><a id="'+currItem+'" class="notify-me" title="Be alerted as soon as this is available" style="font-size: 9pt;" \
			href="/notifyme.php?item='+currItem+'&amp;type=itemrestock" target="notify_'+currItem+'"></a>\
			</div>');
		    $('#'+master+' strong').show();  
		break;
		case "discontinued":
			if($('#'+master+' .no-buy')){
				$('#'+master+' .no-buy').hide();
			}
		  	$('#'+master+' #add-to-ajax').html('').hide();
		    $('#'+master+' .price-val strong').hide();
		  break;
                case "free":
                  if($('#'+master+' .no-buy')){
                    $('#'+master+' .no-buy').hide();
                  }
                  $('#'+master+' #add-to-ajax').show().html('<input class="free" id="buyBtn_'+currItem+'" value="Free" type="submit">');
                  $('#'+master+' strong').hide();
                  
                break;
		default:
			if($('#'+master+' .no-buy')){
				$('#'+master+' .no-buy').hide();
			}
		  $('#'+master+' #add-to-ajax').show().html('<input class="add-to-cart" id="buyBtn_'+currItem+'" value="Add to Cart" type="submit">');
		  $('#'+master+' strong').show();
		}
		$('#'+master+' .price-val span span').html(price);
        });
    });

	$(".pricing-options select").change();
});

//---------------------------Video Popup on product pages


$(function(){
  $('.videoimg').live('click', function(){
    $(this).siblings(".video").modal({overlayClose:true, escClose: true, closeClass: "close"});
  })
  
  $('.video a').live('click', function(e){
    var id = $(this).attr('id');
    e.preventDefault();
    $.modal.close();
    // alert($(this).attr('class'))
    if($(this).attr('class') == 'add-to-cart'){
      ajaxAddItem(id);
      getCartContents();
    } else{
      window.open('/notifyme.php?item='+id+'&amp;type=itemrestock', 'notify_'+id+'', 'width=400,height=200,resizable,scrollbars=1');
      $.modal.close();
    }
  })
});

//---------------------------Notify when available Popup on product pages


$(function(){
  $('.notify-me').live('click', function(e){
    $('#item-id').attr('value', $(this).attr('id'));
    $("#notify-popup").modal({overlayClose:true, escClose: true, closeClass: "modal-close"});
    return false;
  })
  
  $('#notify-submit').live('click', function(e){
    e.preventDefault();
    var currEmail = $('#notify-email').val();
    var itemCode = $('#item-id').val(); 
    if (currEmail.indexOf("@") == -1){
      $('#notify-popup label').html("Please enter a valid email").css({'color':'red', 'font-weight':'bold'});
    }else{
      var dataString = 'email='+ currEmail + '&item=' + itemCode + '&type=itemrestock&action=Notify+Me';  
      //alert (dataString);return false;  
      $.ajax({  
        type: "POST",  
        url: "/notifyme.php",  
        data: dataString,  
        success: function() {  
          $('#notify-data').html("<p style='color: #075A87; font-size: 18px;margin-top: 15px;'>You will be sent an email when the item or category that you requested information on has been updated.</p>");
        }  
      });
    }
  })
});










