$(document).ready(function(){
   
   $.ajaxSetup ({
   	cache: false
   });
   
   $("#messages").slideDown(2000).delay(5000).fadeOut(5000);

   // validate for news
   $("#joinNews").validate({
     rules: {
       joinEmail	: {required: true, email: true}
     }
   })
   // validate for new products 
   $("#myForm").validate({
     rules: {
       prodName		: "required",
       prodDesc		: "required",
       prodPrice	: {required: true, number: true},
       uploadedfile	: {accept: "png|gif|jpg|jpeg"},
       prodColor	: "required",
       category		: "required",
       inStock		: {required: true, digits: true},
       size			: "required",
       designer		: "required"
     }
   })
   // validate for new user
   $("#myUserForm").validate({
     rules: {
       fname		: "required",
       lname		: "required",
       email		: {required: true, email: true},
       pword		: "required",
       pwordVerify	: {required: true, equalTo: "#pword"},
       fnameShip	: "required",
       lnameShip	: "required",
       addressShip	: "required",
       cityShip		: "required",
       stateShip	: "required",
       countryShip	: "required",
       zipShip		: {required: true, minlength: 5},
       phoneShip	: {required: true, minlength: 8},
       fnameBill	: "required",
       lnameBill	: "required",
       addressBill	: "required",
       cityBill		: "required",
       stateBill	: "required",
       countryBill	: "required",
       zipBill		: {required: true, minlength: 5},
       phoneBill	: {required: true, minlength: 8}
     }
   })
   // validate for lost pass
   $("#myPassForm").validate({
     rules: {
       email		: {required: true, email: true}
     }
   })
   // validate for payment
   $("#secureForm").validate({
     rules: {
       cardName		: "required",
       cardNum		: {required: true, digits: true},
       cardExp		: {required: true, minlength: 5},
       ccv			:	{required: true, minlength: 3},
       readTerms	: "required"
     }
   })
   // validate for feedback
   $("#sendFeedback").validate({
     rules: {
       feedback		: "required"
     }
   })

  // masked input for credit cards
    $("#cardExp").mask("99/99",{placeholder:" "});
    $("#ccv").mask("999",{placeholder:" "});
/*     $(".telephone").mask("9?99999999999",{placeholder:" "}); */
  // masked input for contest
/*
    $("#enterContest input[name=phone]").mask("999-999-9999",{placeholder:" "});
    $("#enterContest input[name=postalCode]").mask("99999",{placeholder:" "});
*/

  $('#jsddm > li').bind('mouseover', jsddm_open);
  $('#jsddm > li').bind('mouseout',  jsddm_timer);

  $("a.fancyMe , .fancyMe").fancybox();
  $("a.fancyBlog").fancybox({
  		'width'		: '100%',
  		'height'	: '100%'
  });

  $("#search1").autocomplete("/../includes/searchQuery.php", {
		matchContains: true,
		selectFirst: false,
		minChars: 0
	});

  var bagCount = $('input[name=thisCount]');
  var bagCountNum = $(bagCount).val();
  if ( $(bagCountNum) >= 1 ) $(bagCount).css('z-index','99');

  $("body").live("click",function(oEvent){
    var oTarget = oEvent.target;
	
	if ( $(oTarget).hasClass('myInfoDesc') ) {
		$(oTarget).next().removeClass('activeTab').addClass('inactiveTab');
		$(oTarget).removeClass('inactiveTab').addClass('activeTab');
		$('.myDesigner').hide();
		$('.myInfo').show();
	}
	if ( $(oTarget).hasClass('myInfoDesigner') ) {
		$(oTarget).prev().removeClass('activeTab').addClass('inactiveTab');
		$(oTarget).removeClass('inactiveTab').addClass('activeTab');
		$('.myDesigner').show();
		$('.myInfo').hide();
	}
	
	// add item to cart
    if ( $(oTarget).hasClass('addCart') ) {
    
     var pid = $(oTarget).attr('pid');
     var currentCount = $('input[name=thisCount]');
     var nCount = $(currentCount).val(); 
     var constraint = $("input[pid=" + pid + "]").val();
     var pTotal = '';
     if ( constraint >= 1 ) {
     $.ajax({
       url		: "/addCart.php",
       data		: { pid: pid , constraint: constraint },
       success	: function(data) {
        var newCount = Number(nCount) + 1;
        $(currentCount).attr('value',newCount);
        $(currentCount).css('z-index','99');
        $(oTarget).next().slideDown();
       },
       error: function(data) {
         alert("The current amount of stock has been exceeded.");
       }
      });
      } else alert('This item is temporarily out of stock'); 
       return false;
     }
	
    // used to process credit card
    if ( $(oTarget).hasClass('submitOK') ) {
	 var secureData = $("#secureForm").serialize();
	 $('.submitSecure').css('opacity','0.5').attr('disabled','disabled');
     $.ajax({
       url: "paymentGateway.php",
       type: 'post',
       data: secureData,
	   dataType: 'json',
       success: function(response) {
       		if ( response.success) {
       		var myOrder = response.myOrder;
       		window.location.href = "https://www.hauteheadquarters.com/receipt.php?myOrder=" + myOrder
       		} else {
       			var errorResponse = response.myError;
				$(".errorResponse").slideDown().html(errorResponse).fadeOut(90000);
				$("input[name=cardNum]").attr('value','');
				$("input[name=cardExp]").attr('value','');
				$("input[name=ccv]").attr('value','');
				$("#readTerms").attr('checked','');
				$(".submitSecure").removeClass('submitOK').attr('disabled','disabled').css('opacity','1');
			}
       },
       error: function(data) {
         alert("There was a problem... Check the fields and try again.");
       }
       });
       return false;
     }

   if ( $(oTarget).hasClass('validateCode') ) {
	 var coupon = $("input[name=coupon]").val();
	 var tax 	= parseFloat( $("input[name=tax]").val() );
	 var st 	= $("input[name=subTotal]");
	 var gt 	= parseFloat($("input[name=grandTotal]").val());
     $.ajax({
       url: "work/checkCoupon.php?code=" + coupon,
       type: 'post',
       data: coupon,
	   dataType: 'json',
       success: function(response) {
       		if ( response.success) {
				// get value of coupon
	       		var myValue 	= response.myValue;
	       		var realValue 	= response.realValue;
	       		var discount	= Math.floor(myValue * st.val());
	       		var newST		= Math.floor(st.val() - discount);
	       		var newGT		= Math.floor(gt + tax - discount);
	       		var couponID	= response.couponID;
	
	       		$.ajax({
	       			url: "work/updateSession.php?v=" + newGT + "&subTotal=" + newST + "&discount=" + discount + "&realValue=" + realValue + "&couponID=" + couponID,
	       			type: 'post'
	       		})
	       		       			
				$('#totalPromo').show()
	 			$('#promoTotal').show().html('$' + discount + '.00' + ' (' + realValue + '%)<br>').animate({ color: "#fe0000" }, 1000).animate({ color: "#333333" }, 1000) 
	       		$('#grandTotal').empty().html('$' + newGT + '.00').animate({ color: "#fe0000" }, 1000).animate({ color: "#333333" }, 1000)
	       		// update new gt and coupon input
	       		$('#couponRemove').remove();
	       		$('#validity').addClass('good').fadeIn().html('The coupon you entered is valid.');
				timedRefresh(1000);
	       		} else {
				$('#validity').addClass('bad').fadeIn().html("The coupon you entered is not valid. Please try again.");
			}
       },
       error: function(data) {
         alert("There was a problem... Check the fields and try again.");
       }
       });
       return false;
     }

   if ( $(oTarget).hasClass('deleteIMG') ) {
     $("#uploadedfile").toggle(); 
     $("#uploadedfile").toggleClass('required');
   }

   if ( $(oTarget).hasClass('hauteFlash') ) {
     $("#hf").toggle();
     $("#hf input").toggleClass('required'); 
/*      $("#uploadedfile").toggleClass('required'); */
   }

   if ( $(oTarget).attr('expandOrder') ) {
     var oid = $(oTarget).attr('oid');
     $.ajax({
       url		: "../work/getUserOrder.php",
       data		: { oid: oid },
       success	: function(data) {
		$('.orderInfoUser[oid=' + oid + ']').fadeToggle('fast').html(data);
       },
       error: function(data) {
         alert("There was a problem... Check the fields and try again.");
       }
       });
       return false;
   }

   if ( $(oTarget).attr('joincontest') ) {
	 var contestData = $('#enterContest').serialize();
	 $.ajax({
       url		: "../work/enterContest.php",
       data		: contestData,
       type		: 'post',
	   dataType	: 'json',
       success	: function(response) {
			if ( response.success ) {
				// success
				var myResponse = response.message;
				$('#enterContest').fadeOut();
				$('#successful').html(myResponse).fadeIn();
			} else {
				// fail
				var myResponse = response.message;
				alert(myResponse)
			}
       },
       error: function(data) {
         alert("All the fields with an asterisk are required. Please check the fields and try again.");
       }
       });
       return false; 
  	}
  	
	if ( $(oTarget).attr('sendFeedback') ) {
		var feedbackData = $('#sendFeedback').serialize();
		$.ajax({
			url:		'../work/sendFeedback.php',
			type:		'post',
			data:		feedbackData,
			error:		function (){
							alert('Please enter feedback.')
						},
			success:	function(){
							$('#sendFeedback').hide();
							$('#feedbackSuccess').fadeIn();
						}
		})
		return false;
	}

  }) // end body live function

  $('.hideAfterClick a').click(function(){
  		$('.hideAfterClick').hide();
  		$('#enterContest').show();
  		return false;
  })
  
   // lazy load for images
   $("img").lazyload({         
     placeholder	: "images/loading.png",
     threshold		: 200,
     effect			: "fadeIn"
   });
   
   $('#wrap').mouseleave(function(){
   	 $('#mover').hide();
   })
     
}) // dom ends

var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open()
{  jsddm_canceltimer();
   jsddm_close();
   $(this).addClass('myActiveLink');
   ddmenuitem = $(this).find('ul').css('display', 'block');
   }

function jsddm_close()
{  if(ddmenuitem) { 
	  ddmenuitem.css('display', 'none'); 
	  $("#jsddm li").removeClass('myActiveLink'); };
}

function jsddm_timer()
{  closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}

document.onclick = jsddm_close;

function setPageTitle() {
   document.title = $('input[name=pageTitle]').val()
}

function sameAsShip() {
   // get variables from shipping form
     var shipForm 	= 'Ship';
   	 var fname 		= $("input[name=fname" + shipForm + "]").val();
   	 var lname 		= $("input[name=lname" + shipForm + "]").val();
   	 var address 	= $("input[name=address" + shipForm + "]").val();
   	 var address2 	= $("input[name=address2" + shipForm + "]").val();
   	 var city 		= $("input[name=city" + shipForm + "]").val();
   	 var state 		= $("select[name=state" + shipForm + "]").val();
   	 var oState 	= $("input[name=otherState" + shipForm + "]").val();
   	 var country 	= $("select[name=country" + shipForm + "]").val();
   	 var zip 		= $("input[name=zip" + shipForm + "]").val();
   	 var phone 		= $("input[name=phone" + shipForm + "]").val();
   // set them into billing
     var billForm = 'Bill';
     $("input[name=fname" + billForm + "]").attr('value',fname);
     $("input[name=lname" + billForm + "]").attr('value',lname);
     $("input[name=address" + billForm + "]").attr('value',address);
     $("input[name=address2" + billForm + "]").attr('value',address2);
     $("input[name=city" + billForm + "]").attr('value',city);
     $("select[name=state" + billForm + "]").attr('value',state);
     $("input[name=otherState" + billForm + "]").attr('value',oState);
     $("select[name=country" + billForm + "]").attr('value',country);
     $("input[name=zip" + billForm + "]").attr('value',zip);
     $("input[name=phone" + billForm + "]").attr('value',phone);
   }

function checkEmail() {
 var e = $('input[name=email]').val();
 $.ajax({
  data: { e: e },
  success: function(data) {
  $('.information').load('emailCheck.php?e=' + e);
  $('.information').fadeIn()
   },
   error: function(data) {
   alert("There was a problem... Check the fields and try again.");
   }
 });
}

// for the as seen, hides fields
function hideMyFields() {
 var hideFields = "#hideFields";
 $(hideFields).toggle(0);
 $('#myForm').toggleClass('isAsSeen');
 if ( $('#myForm').hasClass('isAsSeen') ) $('input[name=prodPrice] , input[name=prodColor] ,select[name=category] , input[name=inStock] , input[name=size] , input[name=designer]').attr('disabled','disabled');
 else $('input[name=prodPrice] , input[name=prodColor] ,select[name=category] , input[name=inStock] , input[name=size] , input[name=designer]').removeAttr('disabled');
}

function countViewed(pid) {
     $.ajax({
       url		: "/work/countViewed.php",
       data		: { pid	: pid },
       success	: function() {
         $("body").delay(1000);
       }/*
,
       error: function(data) {
         alert("There was a problem...");
       }
*/
       });
       return false;
}
function checkContest() {
     $.ajax({
      url		: "/work/checkContests.php",
 	  dataType: 'json',
      success	: function(response) {
      	if ( response.success) {
			$('.contestMessage').html(response.message); 
        } else {
			$('.contestMessage').html(response.message + " <a href='https://www.hauteheadquarters.com/admin/contest.php'>Item #" + response.pid + '</a>');
			$('input[name=contest]').attr('disabled','disabled');
        }
       },
       error: function() {
         alert("There was a problem... Check the fields and try again.");
       }
       });
   return false;
}

function secureCheck() {
 $('.submitSecure').removeAttr('disabled').addClass('submitOK');
}

function addShipping() {
 var hGT = Number($("#hiddenGT").val());
 $("input[name=preGrandTotal]").attr('value',hGT);
}

function showShip() {
 var myGT = Number($("input[name=grandTotal]").val());
 var myShip = Number($("select[name=shipping]").val());
 var newGT = myShip + myGT;

	// change that value from crazy 098098090.98789712789 to 90.98
    var i = parseFloat(newGT);     
    
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    // then print the new 's'
    $("#hideMe").show();
	$("#showMe").hide();
    $("#grandTotal").html('$' + s).animate({ color: "#fe0000" }, 1000).animate({ color: "#333333" }, 1000).css('font-weight','bold');
//    $("#hiddenGT").attr('value',s);
}

// packing slip
function printSlip(oid) {
 alert(oid);
 }
 
// add tracking number
function showTrack(oid) {
 $('div[order=' + oid + ']').toggle()
}
function addTracking(orderNum) {
	var myTracking = $('input[orderNum=' + orderNum + ']').val();
		$.ajax({
		url		: "/work/addTrack.php?tracking=" + myTracking + "&orderNum=" + orderNum,
		type	: "post",
		success	: function() {
         	var myTracking 	= '';
         	var orderNum 	= '';
      	 }
       });
	
       return false;
}

// timeout refresh
function timedRefresh(timeoutPeriod) {
	setTimeout("location.reload(true);",timeoutPeriod);
}

