/* ----- popups ------*/ 
function openPopup(url, width, height, scrollbars){
	features = "toolbar=no,menubar=no,location=no,"+(scrollbars ? "scrollbars=yes," : "")+"resizable=yes,width=" + width + ",height=" + height + "";
	window.open(url,"",features);
}

function openHelpPopup(url){
	openPopup(url, 400, 500, true);
}

function openHelpPopupContext(helpfile){
	openHelpPopup(helpfile);
}

/* ----- Cart ------*/ 

 function setCardLinkState(essay_id, is_in){
	     $("a.buttonCart").each(function(index, obj){
				if ($(obj).attr("id") == essay_id){						 
					if (is_in)
					    $(obj).addClass("in-cart").text('In Cart');
					else 	
					    $(obj).removeClass("in-cart").text('Add to Cart'); 
				}
         });
   }	
   
$(document).ready(function(){
  					   
						   
   $("a.buttonCart").click(function(e){
	   e.stopPropagation();
	   var essay_id = $(this).attr("id");
	   var is_read_essay_page = $(this).hasClass("is-read-page");
	   var obj = $(this);
	   $.ajax({type: "POST",
			   url : "/process-cart.php",
			   cache: false,
			   data : {id: essay_id, action: 'add'},
			   dataType: 'json',
			   error: function (XMLHttpRequest, textStatus, errorThrown) {
				        alert(textStatus);
			          },
			   success: function (data, textStatus) {
				           if (data['is_error']){
						       alert(data['error']);
							   if (data['in_cart'])
							      setCardLinkState(essay_id, true);
						   } else {
							   if (!is_read_essay_page){
						            $("#cart-content").html(data['content']);
									setCardLinkState(essay_id, true);
							   }
							   else  
							       setCardLinkState(essay_id, true);
						   }
                        }
		});
   });
   
   $("a.internal-help").click(function(){
	     var attr_id = $(this).attr('id');
		 // help-link-
		 var element_id = attr_id.substr(10, attr_id.length-10);
		 if ($("#"+element_id).is(":visible"))
		    $("#"+element_id).hide();
		 else   
		    $("#"+element_id).show();
	     return false;
	 });
						   
});

function deleteFromCart(link_obj){
	   var item_id = $(link_obj).attr("id");
	   $.ajax({type: "POST",
			   url : "/process-cart.php",
			   cache: false,
			   data : {item_id: item_id, action: 'remove'},
			   dataType: 'json',
			   error: function (XMLHttpRequest, textStatus, errorThrown) {
				        alert(textStatus);
			          },
			   success: function (data, textStatus) {
				           if (data['is_error'])
						       alert(data['error']);
						   else {
						       $("#cart-content").html(data['content']);
							   setCardLinkState(data['id'], false);
						   }
                        }
		});
}