// JavaScript Document

var cartTimeOut = 5000;
var postedData = "";
var options = [];
function showAdded2Cart(data) {
	if (data=="1") {
		//products added
		$("#added").children("span[rel=qty]").text($("#quantity").val());
		$("#added").children("span[rel=item]").text($("#productReview > h3 > em").text());
		$("#added").show("slide");
		$("#quantity").val("-cantitate-").removeAttr('disabled');
		setTimeout(function() {
			$("#added").hide("blind");
		}, cartTimeOut-300);
		_gaq.push(['_trackEvent',"Product","Add to cart"]);
	} else {
		//products not added
		$("#notAdded").show("blind");
	}
}

function addToCart()
 {
	ah = $("#attribute_hidden").val(); 
	av = $("#attribute").val(); 
	if (ah)  var attribute=ah;
	else if (av) var attribute = $("#attribute").children(":selected").val();	
	var quantity=$("#quantity").val();
	var product=$("#product").val();
	if (attribute!='')
	{
	if (quantity!='' && !(isNaN(quantity)))
	 {
	  $("input[class=product]").attr("disabled","disabled");
	  //var url='cart/changeCart.php?id='+product+'&aid='+attribute+'&quantity='+quantity;
	  $.ajax({
		url: 'cart/changeCart.php',
		data: {id: product, aid: attribute, quantity: quantity, ajax:"ajax"},
		success: showAdded2Cart,
		dataType: "text"
	  });
	  //setFrameSrc(url);
	 }else {alert('Va rog introduceti o cantitate!'); return false}
	}else {alert('Va rog alegeti un atribut!'); return false;}
	return true;
 }

function oldaddToCart()
 {
	ah = $("#attribute_hidden").val(); 
	av = $("#attribute").val(); 
	if (ah)  var attribute=ah;
	else if (av) var attribute = $("#attribute").children(":selected").val();	
	var quantity=$("#quantity").val();
	var product=$("#product").val();
	if (attribute!='')
	{
	if (quantity!='' && !(isNaN(quantity)))
	 {
	  var url='cart/changeCart.php?id='+product+'&aid='+attribute+'&quantity='+quantity;
	  setFrameSrc(url);
	 }else {alert('Va rog introduceti o cantitate!'); return false}
	}else {alert('Va rog alegeti un atribut!'); return false;}
	return true;
 }


function showAdd() {
	setTimeout(function(){
		$("#item2Add").show("slide");
	},cartTimeOut);
}


function showResponse(data) {
	if (data=="1") {
		$("#postWait").hide("blind", options, "normal",callbackSuccess);
	}
	else {
		$("#postWait").hide("blind", options, "normal",callbackFail);
	}		
}
function callbackSuccess() {$("#successPost").show("blind", 300, hideSuccess);}
function callbackFail() {$("#errorPost").show("blind", 300, hideError);}

function hideSuccess() {
	setTimeout(function(){
		$("#successPost").hide("blind");
		$("#spyComments").show("blind");
	}, 3000);
}

function hideError() {
	setTimeout(function(){
		$("#errorPost").hide("blind");
		$("#spyComments").show("blind");
	}, 3000);
}

function postCommentData() {
	$("#userReviewForm").hide("blind");
	$("#postWait").show("blind");
	setTimeout($("#postWait").hide("blind", options, "normal",callbackSuccess),7000);
	$.post(
	  "/userReviews/opinion.php",
	  $("#userReviewForm").serialize(),
	  showResponse,
	  "text"
	);
}

function showAdded2Fav(data) {
	if (data=="1") {
		$("#favAdd").hide("blind");
		$("#favadded").show("blind");
		_gaq.push(['_trackEvent',"Product","Favourited"]);
		setTimeout(function() {
			$("#favAdd")
			.attr("rel", "seeFav")
			.attr("value", "Vezi produse favorite")
			.show("blind");
			
			$("#favadded").hide("blind");
		},5000);
	}
}

function addFavourite(status, idP) {
	if (status=="noAuth") {
		if (confirm('Pentru a putea adauga produsul in lista de favorite trebuie sa fiti autentificat. Doriti sa va autentificati?'))
			location.href='/users/login.php';
	} else {
		$.ajax({
		url: '/wishlist/changeWishlist.php',
		data: {id: idP, quantity:1, action: "change", ajax:"ajax"},
		success: showAdded2Fav,
		dataType: "text"
	  });
	}
}

function favoriteAdd() {
	status = $(this).attr("rel");
	if (status=="seeFav") {location.href='/wishlist/wishlist.php';}
	if (status=="addFav" || status=="noAuth") {addFavourite(status, $(this).attr("xidx"))}
}

function announcerClick() {
		datas=$("#notAvailable").attr("cdata");
		$.ajax({
		url: '/announcer/index.php',
		data:datas,
		processData: false,
		dataType: "html", 
		success: function() {
			datas=$("#notAvailable").attr("cdata");
			if (datas.indexOf("&action=cancel")<=0) {
				$("#NAmessage").empty().text("Veti fi anuntat cand acest produs devine disponibil.");
				$("#notAvailable").attr("value", "Anuleaza notificarea").attr("cdata", datas+"&action=cancel");
				}
			else {
				$("#NAmessage").empty().text("Notificarea a fost anulata.");
				$("#notAvailable").attr("value", "Anunta-ma cand revine").attr("cdata", datas.substring(0,datas.indexOf("&action=cancel")));				
			}
			}
			
	  });
}


$(document).ready(function() {
	$("#addProduct").click( function() {
		if (addToCart())$("#item2Add").effect("transfer",{ to: $("#sendOrder")}, cartTimeOut/4,showAdd).hide("blind");
		return false;
	})	
		
	$("[rel=gallery]").fancybox({
	 'padding': 10,
	 'zoomSpeedIn': 700,
	 'zoomSpeedOut': 1000,
	 'overlayShow': true,
	 'enableEscapeButton': true,
	 'easingIn': 'easeOutBack',
	 'easingOut': 'easeInBack',
	 'centerOnScroll': true,
	 'titlePosition': 'inside'
	});
	 
	$("#zoom").click(function (){
	 $("a#thumbOne").click();
	 return false;
	});
	
	$("#showReviewForm").click(function(){
		$("#userReviewForm").show("blind");
		$(".oppinion").hide("highlight");
		$("#spyComments").hide("blind");
		return false;
	});
	
	$("#reviewFormReset").click(function() {
		$("#userReviewForm").hide("blind");
		$(".oppinion").show("highlight");
		$("#spyComments").show("blind");
	});
	
	$("#postComment").click(function() {
		postCommentData();
		return false;
	});
	
	$("#repostComment").click(function() {
		postCommentData();
		return false;
	});
	
	$("span[rel=showSpy]").click(function(){
		$("[rel=formStatus]").hide();
		$("#spyComments").show("blind");
	 })
	
	$("#sendOrder").click(function(){location.href='/cart/checkout.php'})
	
	$("#favAdd").click(favoriteAdd);
	
	$("#notAvailable").click(announcerClick);
	
});	





(function ($) {
    
$.fn.simpleSpy = function (limit, interval) {
    limit = limit || 3;
    interval = interval || 4000;
    
    return this.each(function () {
        // 1. setup
            // capture a cache of all the list items
            // chomp the list down to limit li elements
        var $list = $(this),
            items = [], // uninitialised
            currentItem = limit,
            total = 0, // initialise later on
            height = $list.find('> li:first').height();
            
        // capture the cache
        $list.find('> li').each(function () {
            items.push('<li>' + $(this).html() + '</li>');
        });
        
        total = items.length;
        
        $list.wrap('<div class="spyWrapper" />').parent().css({ height : height * limit });
        
        $list.find('> li').filter(':gt(' + (limit - 1) + ')').remove();

        // 2. effect        
        function spy() {
            // insert a new item with opacity and height of zero
            var $insert = $(items[currentItem]).css({
                height : 0,
                opacity : 0,
                display : 'none'
            }).prependTo($list);
                        
            // fade the LAST item out
            $list.find('> li:last').animate({ opacity : 0}, 1000, function () {
                // increase the height of the NEW first item
                $insert.animate({ height : height }, 1000).animate({ opacity : 1 }, 1000);
                
                // AND at the same time - decrease the height of the LAST item
                // $(this).animate({ height : 0 }, 1000, function () {
                    // finally fade the first item in (and we can remove the last)
                    $(this).remove();
                // });
            });
            
            currentItem++;
            if (currentItem >= total) {
                currentItem = 0;
            }
            
            setTimeout(spy, interval)
        }
        
        spy();
    });
};
    
})(jQuery);

