$(document).ready(function(){
	$("#variations input:radio").removeAttr("checked");

	$("#variations input:radio").each(function(index){
	    $(this).attr("id",index);
	});

	$("li.ui-tab a").each(function(index){
	    $(this).attr("rel",index);
	    
	});

	$("li.ui-tab a").click(function(){
	    var index = $(this).attr("rel");
	    $('#variations input:radio[id=' + index + ']').attr("checked", "checked");
	});

});

$(document).ready(function(){
	var activeElement=null;
	$("#variations input:radio").each(function(index){
		$(this).click(function(){
			if(activeElement!=null){
				$(activeElement).addClass('ui-tabs-hide')
			}
			var element=$("#tabs-"+index);
			element.removeClass('ui-tabs-hide');
			activeElement=element;
			
		});
	});
	
	/*
	$("input[name=ProductItemCountList[]]").each(function(){
		if($(this).val()>3){
			console.log($(this));
			$(this).css({"background-color":"red"});
			$(this).focus();
		}
		});
	*/
	
});

function initializeDialog(titleText,actionUrl,textArray){
$(document).ready(function(){
	$('#dialog').dialog('destroy');
	$('#dialog').dialog({
			autoOpen: false,
    		height: 200,
    		width: 410,
    		modal: true,
    		title: titleText,
    		closeText: 'Close',
    		buttons: {
					'OK': function() {
						var formElement =$(this).find("form");
						rbElement = $("#dialog input:checked");
						if($(rbElement).attr('disabled') == true){
							return false;
						}
						contentObjectId=$(rbElement).val();
						obj=$(rbElement).parents("li:first");
						data={ContentObjectID:contentObjectId};
						$("#spinner").show();
						$.post(actionUrl,data,
								function(){
								//this part if run on the basket page	
								if($("div#shop").length){
										handleProductVariationUpdate(obj,function(){
												$("div.shop-wrapper form").load("/shop/basket/ div.shop-basket",function(){
													$(this).fadeOut();
													$(this).fadeIn("slow");
												});
										});
								 }
								else{
										
										handleProductVariationUpdate(obj);
								}
						});
						$(this).dialog('close');
					 }, 
					 'Cancel': function(){
						 $(this).dialog('close');
					 }
			},
			Cancel: function() {
				$(this).dialog('close');
			}
	});
	
	$('input[name="productvariation"]').each(function(index,obj){
		id=$(this).val();
		imageClass="small";
		updaterUrl="/ezjscore/call/ajaxproduct::getproduct::"+id+"::"+imageClass+"::"+'yes';
		jQuery.ajax({
	         url:    updaterUrl,
	         async:   false,
	         success: function(result,status){
						if(result=="sold"){
							updateRadioButtonText(obj);
						}
					  }			
		}); 
		
		
	});
	
	setupProductVariations();
	
	
  })
}//end function

function updateRadioButtonText(obj){
	li=$(obj).parents("li:first");
	$(obj).attr('disabled','disabled');
	$(obj).removeAttr("checked");
	$(li).append('<br/><div>'+textArray['maxreached']);
	$(li).find("div").addClass("max_reached");

	
}



function setupProductVariations(){
	$('.product_variation_enabled').click(function(){
		var formParent=$(this).parents('form:first').parent();
		$('#dialog').html(formParent.html());
		$('#dialog').find(".productboxvitae").hide();
		$('#dialog').find('.small_embed_price').hide();
		$('#dialog').find(".options").show();
		$('#dialog').find(".product_variation_enabled").hide();
		$('#dialog').find(".end-button").hide();
		var dialog = $('#dialog');
		dialog.dialog('open');
		$("input:radio[id=" + $("input:radio:checked").attr('id') + "]").attr('checked', true);
		if(!$('#dialog input').is(':checked')){
				$("#dialog input:radio:first").attr('checked',true);
			}
	
		return false;
	});
}


function handleProductVariationUpdate(updateObject,callback){
	retrieveBasket(function(){
		$("div.shopping-info").fadeOut(800).fadeIn(800).fadeOut(400).fadeIn(400).fadeOut(200).fadeIn(100);
		imageClass="small";
		updaterUrl="/ezjscore/call/ajaxproduct::getproduct::"+contentObjectId+"::"+imageClass+"::"+'yes';
		currentElement=$("#"+contentObjectId);
		$.post(updaterUrl,null,
				function(result,status){
					if(result=="sold"){
						updateRadioButtonText(updateObject);
					}
					if(typeof callback=="function"){
						callback();
					}
					$("#spinner").hide();
				}
			);
		});
		
}


/* attempte at getting many elements to work on each page */
$(document).ready(function(){
	disabledIds=$('.product_container');
	retrieveBasket();
	$.each(disabledIds,function(index,value){
		imageClass="small";
		if(index==0){
			imageClass="articleimage";
		}
		containerElement=$(value).parent(".orderbutton_container:first");
		formElement = $(value).parents('form:first');
		objId=$(formElement).attr('class').indexOf("_")+1;
		contentObjectId=$(formElement).attr('class').substr(objId);
		//this is not sufficient if the input is not in the html result
		//contentObjectId=$(formElement).find('input[name="ContentObjectID"]').val();
		jQuery.ajax({
	         url:    '/ezjscore/call/ajaxproduct::getproduct::'+contentObjectId+'::'+imageClass 
	                  ,
	         success: function(result) {
							$(containerElement).html(result);
							var newSubmitButton=$(containerElement).find(".product_variation_disabled:first");
							addCallbackListener(newSubmitButton,setup);
							

					 },
	         async:   false
	    });          
		
	});
	
		
});

function retrieveBasket(callback){
	if($("div.shopping-info").length){
		if(callback){
			$("strong.item_counter").load("/ezjscore/call/ajaxbasket::getbasket",callback)
		}
		else{
			$("strong.item_counter").load("/ezjscore/call/ajaxbasket::getbasket");
		}
	}
	//this is typically used on the basket page
	else if(typeof callback=="function"){
		callback();
	}
	
}

function addCallbackListener(element,callbackfunction){
	$.each(element,function(index,value){
			if($(value).hasClass("nopurchase")){
				addToolTip(value);
			}	
			else{
				$(value).click(callbackfunction);
			}
			
			
	});
	
}

function addToolTip(obj){
	$(obj).removeAttr("disabled");
	$(obj).click(function(){return false;});
	$(obj).qtip({
		   content: VitaeConfig.texts['maxreached'],
		   show:'mouseover',
		   hide:'mouseout',
		   position: {
			      my: 'top left', 
			      at:'right top'
		   }
		  
		});
}
 
	

//new solution fixing object reference
function handleCallback(object,imageClass,callback){
	if("div.shopping-info"){
			$("div.shopping-info").fadeOut(800).fadeIn(800).fadeOut(400).fadeIn(400).fadeOut(200).fadeIn(100);
		}
	if(callback){
		callback();
	}
	else if (imageClass!=''){
			containerElement=$(object).parent(".orderbutton_container:first");
			var formElement = $(object).parents('form:first');
			var contentObjectId=$(formElement).find('input[name="ContentObjectID"]').val();
			$(containerElement).load("/ezjscore/call/ajaxproduct::getproduct::"+contentObjectId+"::"+imageClass,function(){
				var newSubmitButton=$(containerElement).find(".product_variation_disabled:first");
				if(!$(newSubmitButton).length){
					$('input[name="ContentObjectID"]').each(function(){
							cid=$(this).attr('value');
							if(cid==contentObjectId){
								//update other elements with the same id, basically remove the button for shopping
								$(this).parent(".orderbutton_container:first").load("/ezjscore/call/ajaxproduct::getproduct::"+contentObjectId+"::"+imageClass);
							}
					});
				}else{
					addCallbackListener(newSubmitButton,setup);
				}
			});
	}
	
}





function setup(){
		submitElement=$(this);
		var formElement = $(this).parents('form:first');
		var imageClass=$(formElement).find('input[name="ProductImageSize"]').val();
		var thisPage = document.location;
		var actionURL="/ezjscore/call/ajaxbasketutil::addproductinbasket";
		var contentObjectId=$(formElement).find('input[name="ContentObjectID"]').val();
		data = {ContentObjectID:contentObjectId};
		$("#spinner").show();
		$.post(actionURL,data,
			function(){
				if($("div.shopping-info").length){
					$("strong.item_counter").load("/ezjscore/call/ajaxbasket::getbasket",
							function(response,status,xhr){
								$("#spinner").hide();
								handleCallback($(submitElement),imageClass);
							});	
				}
				else{
					handleCallback(contentObjectId,imageClass,function(){
						$("#spinner").hide();
						$("#shoptable").load("/shop/basket/ table.list",function(){
							$(this).fadeOut();
							$(this).fadeIn("slow");
							$("#vitaeproduct_"+contentObjectId).fadeOut();
						});
					});
				}
			});
		return false;
}

function parseXML(xml){
	$(xml).find("item").each(function()
			  {
				$("div.shopping-info div.action_box strong.item_counter").append($(this).attr("count"));
			    $("div.shopping-info").show();
			    
			  });
	
}
